X-Git-Url: https://git.openstreetmap.org/rails.git/blobdiff_plain/6c3a31d06c8b8dab8b141c5ae54aaad55614b721..be0d3b49fd7cbb68f09c33d68edb20fe51b0ae2a:/vendor/assets/iD/iD/mapillary-js/mapillary.js diff --git a/vendor/assets/iD/iD/mapillary-js/mapillary.js b/vendor/assets/iD/iD/mapillary-js/mapillary.js index bcc3d7325..40cbd5b8f 100644 --- a/vendor/assets/iD/iD/mapillary-js/mapillary.js +++ b/vendor/assets/iD/iD/mapillary-js/mapillary.js @@ -1,4 +1,269 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Mapillary = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o maxX) maxX = p[0]; + if (!i || p[1] > maxY) maxY = p[1]; + } + + var width = maxX - minX; + var height = maxY - minY; + var cellSize = Math.min(width, height); + var h = cellSize / 2; + + // a priority queue of cells in order of their "potential" (max distance to polygon) + var cellQueue = new Queue(null, compareMax); + + if (cellSize === 0) return [minX, minY]; + + // cover polygon with initial cells + for (var x = minX; x < maxX; x += cellSize) { + for (var y = minY; y < maxY; y += cellSize) { + cellQueue.push(new Cell(x + h, y + h, h, polygon)); + } + } + + // take centroid as the first best guess + var bestCell = getCentroidCell(polygon); + + // special case for rectangular polygons + var bboxCell = new Cell(minX + width / 2, minY + height / 2, 0, polygon); + if (bboxCell.d > bestCell.d) bestCell = bboxCell; + + var numProbes = cellQueue.length; + + while (cellQueue.length) { + // pick the most promising cell from the queue + var cell = cellQueue.pop(); + + // update the best cell if we found a better one + if (cell.d > bestCell.d) { + bestCell = cell; + if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes); + } + + // do not drill down further if there's no chance of a better solution + if (cell.max - bestCell.d <= precision) continue; + + // split the cell into four cells + h = cell.h / 2; + cellQueue.push(new Cell(cell.x - h, cell.y - h, h, polygon)); + cellQueue.push(new Cell(cell.x + h, cell.y - h, h, polygon)); + cellQueue.push(new Cell(cell.x - h, cell.y + h, h, polygon)); + cellQueue.push(new Cell(cell.x + h, cell.y + h, h, polygon)); + numProbes += 4; + } + + if (debug) { + console.log('num probes: ' + numProbes); + console.log('best distance: ' + bestCell.d); + } + + return [bestCell.x, bestCell.y]; +} + +function compareMax(a, b) { + return b.max - a.max; +} + +function Cell(x, y, h, polygon) { + this.x = x; // cell center x + this.y = y; // cell center y + this.h = h; // half the cell size + this.d = pointToPolygonDist(x, y, polygon); // distance from cell center to polygon + this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell +} + +// signed distance from point to polygon outline (negative if point is outside) +function pointToPolygonDist(x, y, polygon) { + var inside = false; + var minDistSq = Infinity; + + for (var k = 0; k < polygon.length; k++) { + var ring = polygon[k]; + + for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + var a = ring[i]; + var b = ring[j]; + + if ((a[1] > y !== b[1] > y) && + (x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0])) inside = !inside; + + minDistSq = Math.min(minDistSq, getSegDistSq(x, y, a, b)); + } + } + + return (inside ? 1 : -1) * Math.sqrt(minDistSq); +} + +// get polygon centroid +function getCentroidCell(polygon) { + var area = 0; + var x = 0; + var y = 0; + var points = polygon[0]; + + for (var i = 0, len = points.length, j = len - 1; i < len; j = i++) { + var a = points[i]; + var b = points[j]; + var f = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * f; + y += (a[1] + b[1]) * f; + area += f * 3; + } + if (area === 0) return new Cell(points[0][0], points[0][1], 0, polygon); + return new Cell(x / area, y / area, 0, polygon); +} + +// get squared distance from a point to a segment +function getSegDistSq(px, py, a, b) { + + var x = a[0]; + var y = a[1]; + var dx = b[0] - x; + var dy = b[1] - y; + + if (dx !== 0 || dy !== 0) { + + var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy); + + if (t > 1) { + x = b[0]; + y = b[1]; + + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = px - x; + dy = py - y; + + return dx * dx + dy * dy; +} + +},{"tinyqueue":241}],2:[function(require,module,exports){ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Ported from Webkit + * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h + */ + +module.exports = UnitBezier; + +function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p2y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier.prototype.sampleCurveX = function(t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; +}; + +UnitBezier.prototype.sampleCurveY = function(t) { + return ((this.ay * t + this.by) * t + this.cy) * t; +}; + +UnitBezier.prototype.sampleCurveDerivativeX = function(t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; +}; + +UnitBezier.prototype.solveCurveX = function(x, epsilon) { + if (typeof epsilon === 'undefined') epsilon = 1e-6; + + var t0, t1, t2, x2, i; + + // First try a few iterations of Newton's method -- normally very fast. + for (t2 = x, i = 0; i < 8; i++) { + + x2 = this.sampleCurveX(t2) - x; + if (Math.abs(x2) < epsilon) return t2; + + var d2 = this.sampleCurveDerivativeX(t2); + if (Math.abs(d2) < 1e-6) break; + + t2 = t2 - x2 / d2; + } + + // Fall back to the bisection method for reliability. + t0 = 0.0; + t1 = 1.0; + t2 = x; + + if (t2 < t0) return t0; + if (t2 > t1) return t1; + + while (t0 < t1) { + + x2 = this.sampleCurveX(t2); + if (Math.abs(x2 - x) < epsilon) return t2; + + if (x > x2) { + t0 = t2; + } else { + t1 = t2; + } + + t2 = (t1 - t0) * 0.5 + t0; + } + + // Failure. + return t2; +}; + +UnitBezier.prototype.solve = function(x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); +}; + +},{}],3:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -34,22 +299,22 @@ function placeHoldersCount (b64) { function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) + return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr + var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) - arr = new Arr(len * 3 / 4 - placeHolders) + arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 - for (i = 0, j = 0; i < l; i += 4, j += 3) { + for (i = 0; i < l; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF @@ -114,9 +379,9 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],2:[function(require,module,exports){ +},{}],4:[function(require,module,exports){ -},{}],3:[function(require,module,exports){ +},{}],5:[function(require,module,exports){ /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan @@ -224,7 +489,7 @@ module.exports = (function split(undef) { return self; })(); -},{}],4:[function(require,module,exports){ +},{}],6:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -395,6 +660,10 @@ process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); @@ -406,12 +675,11 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],5:[function(require,module,exports){ -(function (global){ +},{}],7:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * - * @author Feross Aboukhadijeh + * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ @@ -420,80 +688,57 @@ process.umask = function() { return 0; }; var base64 = require('base64-js') var ieee754 = require('ieee754') -var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) * * 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: - * - * - 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. - * - * - 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. + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} function typedArraySupport () { + // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + return arr.foo() === 42 } catch (e) { return false } } -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -function createBuffer (that, length) { - if (kMaxLength() < length) { +function createBuffer (length) { + if (length > K_MAX_LENGTH) { throw new RangeError('Invalid typed array length') } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf } /** @@ -507,10 +752,6 @@ function createBuffer (that, length) { */ function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { @@ -518,33 +759,38 @@ function Buffer (arg, encodingOrOffset, length) { 'If encoding is specified then the first argument must be a string' ) } - return allocUnsafe(this, arg) + return allocUnsafe(arg) } - return from(this, arg, encodingOrOffset, length) + return from(arg, encodingOrOffset, length) } -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) } -function from (that, value, encodingOrOffset, length) { +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) + return fromString(value, encodingOrOffset) } - return fromObject(that, value) + return fromObject(value) } /** @@ -556,22 +802,14 @@ function from (that, value, encodingOrOffset, length) { * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } + return from(value, encodingOrOffset, length) } +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') @@ -580,20 +818,20 @@ function assertSize (size) { } } -function alloc (that, size, fill, encoding) { +function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { - return createBuffer(that, size) + return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) } - return createBuffer(that, size) + return createBuffer(size) } /** @@ -601,34 +839,28 @@ function alloc (that, size, fill, encoding) { * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) + return alloc(size, fill, encoding) } -function allocUnsafe (that, size) { +function allocUnsafe (size) { assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that + return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) + return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) + return allocUnsafe(size) } -function fromString (that, string, encoding) { +function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } @@ -638,32 +870,30 @@ function fromString (that, string, encoding) { } var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) + var buf = createBuffer(length) - var actual = that.write(string, encoding) + var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) + buf = buf.slice(0, actual) } - return that + return buf } -function fromArrayLike (that, array) { +function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) + var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + buf[i] = array[i] & 255 } - return that + return buf } -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - +function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } @@ -672,49 +902,43 @@ function fromArrayBuffer (that, array, byteOffset, length) { throw new RangeError('\'length\' is out of bounds') } + var buf if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) + buf = new Uint8Array(array) } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) + buf = new Uint8Array(array, byteOffset) } else { - array = new Uint8Array(array, byteOffset, length) + buf = new Uint8Array(array, byteOffset, length) } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf } -function fromObject (that, obj) { +function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 - that = createBuffer(that, len) + var buf = createBuffer(len) - if (that.length === 0) { - return that + if (buf.length === 0) { + return buf } - obj.copy(that, 0, 0, len) - return that + obj.copy(buf, 0, 0, len) + return buf } if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) + if (isArrayBufferView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) } - return fromArrayLike(that, obj) + return fromArrayLike(obj) } - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) } } @@ -722,11 +946,11 @@ function fromObject (that, obj) { } function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { + if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } @@ -739,7 +963,7 @@ function SlowBuffer (length) { } Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) + return b != null && b._isBuffer === true } Buffer.compare = function compare (a, b) { @@ -785,7 +1009,7 @@ Buffer.isEncoding = function isEncoding (encoding) { } Buffer.concat = function concat (list, length) { - if (!isArray(list)) { + if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } @@ -818,8 +1042,7 @@ function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + if (isArrayBufferView(string) || isArrayBuffer(string)) { return string.byteLength } if (typeof string !== 'string') { @@ -929,8 +1152,12 @@ function slowToString (encoding, start, end) { } } -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { @@ -977,7 +1204,7 @@ Buffer.prototype.swap64 = function swap64 () { } Buffer.prototype.toString = function toString () { - var length = this.length | 0 + var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) @@ -1081,7 +1308,7 @@ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { + if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } @@ -1110,8 +1337,7 @@ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { + if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { @@ -1213,7 +1439,7 @@ function hexWrite (buf, string, offset, length) { } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i + if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i @@ -1252,15 +1478,14 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { - offset = offset | 0 + offset = offset >>> 0 if (isFinite(length)) { - length = length | 0 + length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } - // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' @@ -1459,7 +1684,7 @@ 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) + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } @@ -1485,18 +1710,9 @@ Buffer.prototype.slice = function slice (start, end) { if (end < start) end = start - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype return newBuf } @@ -1509,8 +1725,8 @@ function checkOffset (offset, ext, length) { } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] @@ -1524,8 +1740,8 @@ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } @@ -1540,21 +1756,25 @@ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | @@ -1564,6 +1784,7 @@ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + @@ -1573,8 +1794,8 @@ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] @@ -1591,8 +1812,8 @@ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength @@ -1609,24 +1830,28 @@ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 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) { + offset = offset >>> 0 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) { + offset = offset >>> 0 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) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | @@ -1636,6 +1861,7 @@ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | @@ -1645,21 +1871,25 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } @@ -1672,8 +1902,8 @@ function checkInt (buf, value, offset, ext, max, min) { Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) @@ -1691,8 +1921,8 @@ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) @@ -1710,89 +1940,57 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value - offset = offset | 0 + 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 - } -} - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) return offset + 2 } -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 - } -} - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } @@ -1813,9 +2011,9 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } @@ -1836,9 +2034,8 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value - offset = offset | 0 + 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 @@ -1846,58 +2043,42 @@ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value - offset = offset | 0 + 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) - } + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) return offset + 4 } @@ -1907,6 +2088,8 @@ function checkIEEE754 (buf, value, offset, ext, max, min) { } function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } @@ -1923,6 +2106,8 @@ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } @@ -1971,7 +2156,7 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] @@ -2040,7 +2225,7 @@ Buffer.prototype.fill = function fill (val, start, end, encoding) { } else { var bytes = Buffer.isBuffer(val) ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) + : new Buffer(val, encoding) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] @@ -2053,11 +2238,11 @@ Buffer.prototype.fill = function fill (val, start, end, encoding) { // HELPER FUNCTIONS // ================ -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g +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, '') + str = str.trim().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 @@ -2067,11 +2252,6 @@ function base64clean (str) { return str } -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) @@ -2194,16 +2374,28 @@ function blitBuffer (src, dst, offset, length) { return i } -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare +// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check +// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 +function isArrayBuffer (obj) { + return obj instanceof ArrayBuffer || + (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && + typeof obj.byteLength === 'number') } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` +function isArrayBufferView (obj) { + return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) +} + +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare +} -},{"base64-js":1,"ieee754":15,"isarray":19}],6:[function(require,module,exports){ +},{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){ 'use strict'; module.exports = earcut; +module.exports.default = earcut; function earcut(data, holeIndices, dim) { @@ -2216,7 +2408,7 @@ function earcut(data, holeIndices, dim) { if (!outerNode) return triangles; - var minX, minY, maxX, maxY, x, y, size; + var minX, minY, maxX, maxY, x, y, invSize; if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); @@ -2234,11 +2426,12 @@ function earcut(data, holeIndices, dim) { if (y > maxY) maxY = y; } - // minX, minY and size are later used to transform coords into integers for z-order calculation - size = Math.max(maxX - minX, maxY - minY); + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; } - earcutLinked(outerNode, triangles, dim, minX, minY, size); + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); return triangles; } @@ -2274,7 +2467,7 @@ function filterPoints(start, end) { 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; + if (p === p.next) break; again = true; } else { @@ -2286,11 +2479,11 @@ function filterPoints(start, end) { } // main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { if (!ear) return; // interlink polygon nodes in z-order - if (!pass && size) indexCurve(ear, minX, minY, size); + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); var stop = ear, prev, next; @@ -2300,7 +2493,7 @@ function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { prev = ear.prev; next = ear.next; - if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { // cut off the triangle triangles.push(prev.i / dim); triangles.push(ear.i / dim); @@ -2321,16 +2514,16 @@ function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { if (ear === stop) { // try filtering points and slicing again if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally } else if (pass === 1) { ear = cureLocalIntersections(ear, triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, size, 2); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, size); + splitEarcut(ear, triangles, dim, minX, minY, invSize); } break; @@ -2358,7 +2551,7 @@ function isEar(ear) { return true; } -function isEarHashed(ear, minX, minY, size) { +function isEarHashed(ear, minX, minY, invSize) { var a = ear.prev, b = ear, c = ear.next; @@ -2372,8 +2565,8 @@ function isEarHashed(ear, minX, minY, size) { maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); // z-order range for the current triangle bbox; - var minZ = zOrder(minTX, minTY, minX, minY, size), - maxZ = zOrder(maxTX, maxTY, minX, minY, size); + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); // first look for points inside the triangle in increasing z-order var p = ear.nextZ; @@ -2424,7 +2617,7 @@ function cureLocalIntersections(start, triangles, dim) { } // try splitting polygon into two and triangulate them independently -function splitEarcut(start, triangles, dim, minX, minY, size) { +function splitEarcut(start, triangles, dim, minX, minY, invSize) { // look for a valid diagonal that divides the polygon into two var a = start; do { @@ -2439,8 +2632,8 @@ function splitEarcut(start, triangles, dim, minX, minY, size) { c = filterPoints(c, c.next); // run earcut on each half - earcutLinked(a, triangles, dim, minX, minY, size); - earcutLinked(c, triangles, dim, minX, minY, size); + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); return; } b = b.next; @@ -2497,7 +2690,7 @@ function findHoleBridge(hole, outerNode) { // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { - if (hy <= p.y && hy >= p.next.y) { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; @@ -2528,7 +2721,7 @@ function findHoleBridge(hole, outerNode) { p = m.next; while (p !== stop) { - if (hx >= p.x && p.x >= mx && + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { tan = Math.abs(hy - p.y) / (hx - p.x); // tangential @@ -2546,10 +2739,10 @@ function findHoleBridge(hole, outerNode) { } // interlink polygon nodes in z-order -function indexCurve(start, minX, minY, size) { +function indexCurve(start, minX, minY, invSize) { var p = start; do { - if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); p.prevZ = p.prev; p.nextZ = p.next; p = p.next; @@ -2582,20 +2775,11 @@ function sortLinked(list) { q = q.nextZ; if (!q) break; } - qSize = inSize; while (pSize > 0 || (qSize > 0 && q)) { - if (pSize === 0) { - e = q; - q = q.nextZ; - qSize--; - } else if (qSize === 0 || !q) { - e = p; - p = p.nextZ; - pSize--; - } else if (p.z <= q.z) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { e = p; p = p.nextZ; pSize--; @@ -2623,11 +2807,11 @@ function sortLinked(list) { return list; } -// z-order of a point given coords and size of the data bounding box -function zOrder(x, y, minX, minY, size) { +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { // coords are transformed into non-negative 15-bit integer range - x = 32767 * (x - minX) / size; - y = 32767 * (y - minY) / size; + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; @@ -2711,7 +2895,8 @@ function middleInside(a, b) { px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { - if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) inside = !inside; p = p.next; } while (p !== a); @@ -2846,7 +3031,7 @@ earcut.flatten = function (data) { return result; }; -},{}],7:[function(require,module,exports){ +},{}],9:[function(require,module,exports){ 'use strict'; var OneVersionConstraint = require('individual/one-version'); @@ -2868,7 +3053,7 @@ function EvStore(elem) { return hash; } -},{"individual/one-version":17}],8:[function(require,module,exports){ +},{"individual/one-version":19}],10:[function(require,module,exports){ 'use strict'; var request = require('./request'); var buildQueryObject = require('./buildQueryObject'); @@ -2969,7 +3154,7 @@ XMLHttpSource['default'] = XMLHttpSource; // commonjs module.exports = XMLHttpSource; -},{"./buildQueryObject":9,"./request":12}],9:[function(require,module,exports){ +},{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){ 'use strict'; module.exports = function buildQueryObject(url, method, queryData) { var qData = []; @@ -2998,7 +3183,7 @@ module.exports = function buildQueryObject(url, method, queryData) { return data; }; -},{}],10:[function(require,module,exports){ +},{}],12:[function(require,module,exports){ (function (global){ 'use strict'; // Get CORS support even for older IE @@ -3015,7 +3200,7 @@ module.exports = function getCORSRequest() { }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],11:[function(require,module,exports){ +},{}],13:[function(require,module,exports){ (function (global){ 'use strict'; module.exports = function getXMLHttpRequest() { @@ -3044,7 +3229,7 @@ module.exports = function getXMLHttpRequest() { }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],12:[function(require,module,exports){ +},{}],14:[function(require,module,exports){ 'use strict'; var getXMLHttpRequest = require('./getXMLHttpRequest'); var getCORSRequest = require('./getCORSRequest'); @@ -3267,7 +3452,7 @@ function onXhrError(observer, xhr, status, e) { module.exports = request; -},{"./getCORSRequest":10,"./getXMLHttpRequest":11}],13:[function(require,module,exports){ +},{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){ (function (global){ !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.falcor=t()}}(function(){var t;return function e(t,n,r){function o(s,u){if(!n[s]){if(!t[s]){var a="function"==typeof require&&require;if(!u&&a)return a(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var p=n[s]={exports:{}};t[s][0].call(p.exports,function(e){var n=t[s][1][e];return o(n?n:e)},p,p.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s1&&!Array.isArray(r)||0===e&&!Array.isArray(r)&&"string"!==o||1===e&&!Array.isArray(r)&&!x(r))return new u(function(t){t.onError(new Error("Invalid argument"))})}return c.create(this,t)},r.prototype.invalidate=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(t=new Array(n);++e0){var n=o.Observable.of(t);return t.get.apply(t,u)["catch"](o.Observable.empty()).concat(n).last().flatMap(function(){return r(e,a)}).filter(function(t){return t})}return o.Observable["return"](t)}if(s>0){var i=u.map(function(t){return a.concat(t)});return e.get.apply(e,i).concat(o.Observable.defer(function(){return r(e,a)})).last().filter(function(t){return t})}return o.Observable.empty()})}},{134:134,159:159}],6:[function(t,e,n){var r=t(134),o=t(13),i=t(8),s=t(118);e.exports=function(t){var e=r.fromPath(t);if(!Array.isArray(e))throw new Error("Model#derefSync must be called with an Array path.");var n=o(this,this._path.concat(e),!1),u=n.path,a=n.value,c=n.found;if(c&&void 0!==a&&(a.$type!==s||void 0!==a.value)){if(a.$type)throw new i;return this._clone({_path:u})}}},{118:118,13:13,134:134,8:8}],7:[function(t,e,n){function r(){this.message=r.message,this.stack=(new Error).stack}r.prototype=new Error,r.prototype.name="BoundJSONGraphModelError",r.message="It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.",e.exports=r},{}],8:[function(t,e,n){function r(t,e){this.message=i,this.stack=(new Error).stack,this.boundPath=t,this.shortedPath=e}var o="InvalidModelError",i="The boundPath of the model is not valid since a value or error was found before the path end.";r.prototype=new Error,r.prototype.name=o,r.message=i,e.exports=r},{}],9:[function(t,e,n){function r(t){this.message="An exception was thrown when making a request.",this.stack=(new Error).stack,this.innerError=t}var o="InvalidSourceError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],10:[function(t,e,n){function r(){this.message="The allowed number of retries have been exceeded.",this.stack=(new Error).stack}var o="MaxRetryExceededError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],11:[function(t,e,n){function r(t,e,n,r,o,h,f){for(var l,d,v=n,y=o,b=r,m=0;;){if(0===m&&b[c]?(m=y.length,d=b[c]):(l=y[m++],d=v[l]),d){var g=d.$type,w=g&&d.value||d;if(m_;_++)x[_]=y[_];y=x}return[v,y]}var o=t(26),i=o.create,s=t(22),u=t(27),a=t(120),c=t(33),p=t(29).promote;e.exports=r},{120:120,22:22,26:26,27:27,29:29,33:33}],12:[function(t,e,n){var r=t(15),o=t(8),i=t(7);e.exports=function(t,e){return function(n,s,u){var a,c,p,h=u[0],f={values:u,optimizedPaths:[]},l=n._root.cache,d=n._path,v=l,y=d.length,b=[];if(y){if(e)return{criticalError:new i};if(v=r(n,d),v.$type)return{criticalError:new o(d,d)};for(a=[],c=0;y>c;++c)a[c]=d[c]}else a=[],y=0;for(c=0,p=s.length;p>c;c++)t(n,l,v,s[c],0,h,f,b,a,y,e);return f}}},{15:15,7:7,8:8}],13:[function(t,e,n){var r=t(17),o=t(8);e.exports=function(t,e,n){var i,s,u,a,c,p=e,h=e;for(i=t._boxed,n=t._materialized,s=t._treatErrorsAsValues,t._boxed=!0,t._materialized=void 0===n||n,t._treatErrorsAsValues=!0,u=r(t,p.concat(null),!0),t._boxed=i,t._materialized=n,t._treatErrorsAsValues=s,p=u.optimizedPath,a=u.shorted,c=u.found,u=u.value;p.length&&null===p[p.length-1];)p.pop();if(c&&a)throw new o(h,p);return{path:p,value:u,shorted:a,found:c}}},{17:17,8:8}],14:[function(t,e,n){function r(t){var e,n,r,o={},i=Object.keys(t);for(n=0,r=i.length;r>n;n++)e=i[n],s(e)||(o[e]=t[e]);return o}function o(t,e,n){Object.keys(t).filter(function(e){return!s(e)&&t[e]}).forEach(function(n){var s=t[n],u=e[n];if(u||(u=e[n]={}),s.$type){var a,c=s.value&&"object"==typeof s.value,p=!t[i];return a=c||p?r(s):s.value,void(e[n]=a)}o(s,u,n)})}var i=t(37),s=t(97);e.exports=function(t){var e={};return o(t,e),e}},{37:37,97:97}],15:[function(t,e,n){e.exports=function(t,e){for(var n=t._root.cache,r=-1,o=e.length;++rw;){if(p=e[w++],null!==p&&(x=_[p],b[b.length]=p),!x){S=void 0,m=!0,E=!1;break}if(f=x.$type,f===a&&void 0===x.value){S=void 0,E=!1,m=y>w;break}if(y>w){if(f===u){if(i(x)){C=!0,S=void 0,E=!1;break}if(l=r(t,v,v,x,x.value),d=l[0],!d){S=void 0,x=void 0,E=!1;break}f=d.$type,x=d,b=l[1].slice(0)}if(f)break}else S=x;_=x}if(y>w&&!C){for(h=w;y>h;++h)if(null!==e[w]){g=!0;break}for(g?(m=!0,S=void 0):S=x,h=w;y>h;++h)null!==e[h]&&(b[b.length]=e[h])}if(S&&f&&(i(S)?S=void 0:s(t,S)),S&&f===c&&!t._treatErrorsAsValues)throw{path:w===y?e:e.slice(0,w),value:S.value};return S&&t._boxed?S=Boolean(f)&&!n?o(S):S:!S&&t._materialized?S={$type:a}:S&&(S=S.value),{value:S,shorted:m,optimizedPath:b,found:E}}},{11:11,118:118,119:119,120:120,25:25,27:27,29:29}],18:[function(t,e,n){var r=t(46);e.exports=function(t,e){var n=t._getValueSync({_boxed:!0,_root:t._root,_treatErrorsAsValues:t._treatErrorsAsValues},e,!0).value,o=n&&n[r];return null==o?-1:o}},{46:46}],19:[function(t,e,n){var r=t(12),o=t(31),i=r(o,!1),s=r(o,!0);e.exports={getValueSync:t(17),getBoundValue:t(13),getWithPathsAsPathMap:i,getWithPathsAsJSONGraph:s}},{12:12,13:13,17:17,31:31}],20:[function(t,e,n){var r=t(29),o=t(25),i=r.promote;e.exports=function(t,e,n,r,s){var u=e.value;s.errors||(s.errors=[]),t._boxed&&(u=o(e)),s.errors.push({path:r.slice(0,n+1),value:u}),i(t,e)}},{25:25,29:29}],21:[function(t,e,n){function r(t,e,n,r,o,i,s){s.requestedMissingPaths.push(r.slice(0,n).concat(e)),s.optimizedMissingPaths.push(o.slice(0,i).concat(e))}var o=t(30),i=o.fastCopy;e.exports=function(t,e,n,o,s,u,a){var c;o.requestedMissingPaths||(o.requestedMissingPaths=[],o.optimizedMissingPaths=[]),c=ny;y++)g=f[y],w[g]||(w[g]={}),w=w[g];g=f[y],w[g]=E?{$type:u}:S,h&&n.paths.push(h.slice(0,r))}else if(0===r)n.json=S;else{for(w=n.json,w||(w=n.json={}),y=0;r-1>y;y++)m=h[y],w[m]||(w[m]={}),x=w,_=m,w=w[m];m=h[y],null!==m?w[m]=S:x[_]=S}}}},{118:118,119:119,120:120,25:25,29:29,37:37}],23:[function(t,e,n){var r=t(27),o=t(26),i=t(29),s=o.remove,u=i.splice,a=t(119),c=t(20),p=t(22),h=t(21),f=t(28),l=t(35);e.exports=function(t,e,n,o,i,d,v,y,b,m,g){var w=e&&e.$type,x=e&&void 0===e.value;return e&&w?void(r(e)?(e[l]||(u(t,e),s(e)),h(t,n,o,d,v,y,b)):w===a?(g&&(v[o]=null),m||t._treatErrorsAsValues?p(t,e,i,o,d,v,y,b,m,g):c(t,e,o,v,d)):(g&&(v[o]=null),(!x||x&&t._materialized)&&p(t,e,i,o,d,v,y,b,m,g))):void(f(t)?p(t,e,i,o,d,v,y,b,m,g):h(t,n,o,d,v,y,b))}},{119:119,20:20,21:21,22:22,26:26,27:27,28:28,29:29,35:35}],24:[function(t,e,n){var r=t(134);e.exports=function(t){var e=r.fromPath(t);if(Array.isArray(e)===!1)throw new Error("Model#getValueSync must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._syncCheck("getValueSync")&&this._getValueSync(this,e).value}},{134:134}],25:[function(t,e,n){var r=t(40);e.exports=function(t){var e,n,o,i=Object.keys(t);for(e={},n=0,o=i.length;o>n;n++){var s=i[n];s[0]!==r&&(e[s]=t[s])}return e}},{40:40}],26:[function(t,e,n){function r(t,e){var n=e[a]||0;e[i+n]=t,e[a]=n+1,t[u]=n,t[s]=e}function o(t){var e=t[s];if(e){for(var n=t[u],r=e[a];r>n;)e[i+n]=e[i+n+1],++n;e[a]=r-1,t[s]=void 0,t[u]=void 0}}var i=t(43),s=t(33),u=t(42),a=t(44);e.exports={create:r,remove:o}},{33:33,42:42,43:43,44:44}],27:[function(t,e,n){var r=t(106);e.exports=function(t){var e=void 0===t.$expires&&-1||t.$expires;return-1!==e&&1!==e&&(0===e||eo;r++,o++)i[r]=t[o];return i}function o(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)null!==e[o]&&(i[n++]=e[o]);return i}function i(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)i[n++]=e[o];return i}e.exports={fastCat:i,fastCatSkipNulls:o,fastCopy:r}},{}],31:[function(t,e,n){var r=t(11),o=t(23),i=t(27),s=t(143).iterateKeySet,u=t(120),a=t(29).promote;e.exports=function c(t,e,n,p,h,f,l,d,v,y,b,m){var g=m,w=v;if(!n||n&&n.$type||h===p.length)return void o(t,n,p,h,f,l,d,w,y,b,g);var x,_;x=p[h];var S="object"==typeof x,E=h+1,C=!1,A=x;if(S&&(C={},A=s(x,C)),void 0!==A||!C.done){var N=y+1;do{g=!1;var k;null===A?k=n:(k=n[A],w[y]=A,d[h]=A);var O=w,P=N;if(k){var j=k.$type,D=j&&k.value||k;if(E_;++_)O[_]=R[_]}}c(t,e,k,p,E,f,l,d,O,P,b,g),C&&!C.done&&(A=s(x,C))}while(C&&!C.done)}}},{11:11,120:120,143:143,23:23,27:27,29:29}],32:[function(t,e,n){"use strict";function r(t){return new r.Model(t)}"function"==typeof Promise?r.Promise=Promise:r.Promise=t(151),e.exports=r,r.Model=t(2)},{151:151,2:2}],33:[function(t,e,n){e.exports=t(40)+"context"},{40:40}],34:[function(t,e,n){e.exports=t(40)+"head"},{40:40}],35:[function(t,e,n){e.exports=t(40)+"invalidated"},{40:40}],36:[function(t,e,n){e.exports=t(40)+"key"},{40:40}],37:[function(t,e,n){e.exports="$modelCreated"},{}],38:[function(t,e,n){e.exports=t(40)+"next"},{40:40}],39:[function(t,e,n){e.exports=t(40)+"parent"},{40:40}],40:[function(t,e,n){e.exports=String.fromCharCode(30)},{}],41:[function(t,e,n){e.exports=t(40)+"prev"},{40:40}],42:[function(t,e,n){e.exports=t(40)+"ref-index"},{40:40}],43:[function(t,e,n){e.exports=t(40)+"ref"},{40:40}],44:[function(t,e,n){e.exports=t(40)+"refs-length"},{40:40}],45:[function(t,e,n){e.exports=t(40)+"tail"},{40:40}],46:[function(t,e,n){e.exports=t(40)+"version"},{40:40}],47:[function(t,e,n){function r(t,e,n,o,s,u,c,p,h,f){if(!_(t)&&!t.$type)for(var l in t)if(l[0]!==a&&"$"!==l[0]&&m(t,l)){var d=t[l],v=g(d)&&!d.$type,y=i(n,o,s,l,d,v,!1,u,c,p,h,f),w=y[0],x=y[1];w&&(v?r(d,e+1,n,x,w,u,c,p,h,f):A(w,x,l,p)&&C(x,b(w),p,u))}}function o(t,e,n,r,o,s,a,h){if(w(n))return S(n,o,s),[void 0,e];y(s,n);var d=n,v=n.value,b=e;if(n=n[p],null!=n)b=n[c]||e;else{var m=0,g=v.length-1;b=n=e;do{var x=v[m],E=g>m,C=i(e,b,n,x,t,E,!0,r,o,s,a,h);if(n=C[0],_(n))return C;b=C[1]}while(m++d,_=i(t,l,e,m,x,!0,n,r,o);if(e=_[0],g(e))return _;l=_[1]}while(d++=h){var x=t[s];for(b=x;d>=w&&b;)x=x[a],m=b.$size||0,d-=m,g===!0&&p(b,m,t,l),b=x;t[s]=t[a]=b,null==b?t[i]=t[u]=void 0:b[u]=void 0}}},{108:108,115:115,34:34,36:36,38:38,39:39,41:41,45:45}],50:[function(t,e,n){var r=t(121),o=t(34),i=t(45),s=t(38),u=t(41),a=t(100);e.exports=function(t,e){if(a(e)&&e.$expires!==r){var n=t[o],c=t[i],p=e[s],h=e[u];e!==n&&(null!=p&&"object"==typeof p&&(p[u]=h),null!=h&&"object"==typeof h&&(h[s]=p),p=n,null!=n&&"object"==typeof n&&(n[u]=e),t[o]=t[s]=n=e,n[s]=p,n[u]=void 0),null!=c&&e!==c||(t[i]=t[u]=c=h||e)}return e}},{100:100,121:121,34:34,38:38,41:41,45:45}],51:[function(t,e,n){var r=t(34),o=t(45),i=t(38),s=t(41);e.exports=function(t,e){var n=t[r],u=t[o],a=e[i],c=e[s];null!=a&&"object"==typeof a&&(a[s]=c),null!=c&&"object"==typeof c&&(c[i]=a),e===n&&(t[r]=t[i]=a),e===u&&(t[o]=t[s]=c),e[i]=e[s]=void 0,n=u=a=c=void 0}},{34:34,38:38,41:41,45:45}],52:[function(t,e,n){function r(t,e){var n=!1;return function(){if(!n&&!t._disposed){n=!0,t._callbacks[e]=null,t._optimizedPaths[e]=[],t._requestedPaths[e]=[];var r=--t._count;0!==r||t.sent||(t._disposable.dispose(),t.requestQueue.removeRequest(t))}}}function o(t){for(var e=[],n=-1,r=0,o=t.length;o>r;++r)for(var i=t[r],s=0,u=i.length;u>s;++s)e[++n]=i[s];return e}var i=t(59),s=t(60),u=0,a=t(57).GetRequest,c=t(76),p=t(78),h=t(119),f=[],l=function(t,e){this.sent=!1,this.scheduled=!1,this.requestQueue=e,this.id=++u,this.type=a,this._scheduler=t,this._pathMap={},this._optimizedPaths=[],this._requestedPaths=[],this._callbacks=[],this._count=0,this._disposable=null,this._collapsed=null,this._disposed=!1};l.prototype={batch:function(t,e,n){var o=this,i=o._optimizedPaths,u=o._requestedPaths,a=o._callbacks,c=i.length;return i[c]=e,u[c]=t,a[c]=n,++o._count,o.scheduled||(o.scheduled=!0,o._disposable=o._scheduler.schedule(function(){s(o,i,function(t,e){if(o.requestQueue.removeRequest(o),o._disposed=!0,o._count){o._merge(u,t,e);for(var n=0,r=a.length;r>n;++n){var i=a[n];i&&i(t,e)}}})})),r(o,c)},add:function(t,e,n){var o,s,u=this,a=i(t,e,u._pathMap);a?(s=a[2],o=a[1]):(s=t,o=e);var c=!1,p=!1;if(o.lengthi){if(null==c){if(e)return!1;c=u[a]=Object.create(null)}if(this.insertPath(t,e,c,i+1,s)===!1)return!1}else u[a]=(c||0)+1,this.length+=1;h.done||(a=f(p,h))}while(!h.done);return!0},r.prototype.removePath=function(t,e,n,r){var o=n||0,i=r||t.length-1,s=e||this.pathmaps[i+1];if(void 0===s||null===s)return!0;var u,a,c=0,p=t[o],h={};u=f(p,h);do if(a=s[u],void 0!==a&&null!==a){if(i>o){c+=this.removePath(t,a,o+1,i);var l=void 0;for(l in a)break;void 0===l&&delete s[u]}else a=s[u]=(a||1)-1,0===a&&delete s[u],c+=1,this.length-=1;h.done||(u=f(p,h))}while(!h.done);return c},r.prototype.getSourceObserver=function(t){var e=this;return i.create(function(n){n.jsonGraph=n.jsonGraph||n.jsong||n.values||n.value,n.index=e.index,t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})},r.prototype._subscribe=function(t){var e=this,n=this.queue;e.pending=!0;var r=!1,o=new a,i=u.create(function(){r||(r=!0,n&&n._remove(e))}),s=new c(o,i);try{o.setDisposable(this.model._source[this.method](this.getSourceArgs()).subscribe(this.getSourceObserver(t)))}catch(h){throw new p(h)}return s},e.exports=r},{143:143,159:159,9:9}],54:[function(t,e,n){function r(t,e){this.total=0,this.model=t,this.requests=[],this.scheduler=e}var o=t(58),i=t(40),s=t(90),u=t(100),a=t(143);r.prototype.set=function(t){return t.paths=a.collapse(t.paths),o.create(this.model,t)},r.prototype._remove=function(t){var e=this.requests,n=e.indexOf(t);-1!==n&&e.splice(n,1)},r.prototype.distributePaths=function(t,e,n){var r,o,i=this.model,s=-1,u=t.length,a=-1,c=e.length,p=[];t:for(;++s-1;){for(var h=r[n-1],f=o[n-1],l=a[n-1]||(a[n-1]=Object.keys(f));l.length>0;){var d=l.pop();if(d[0]!==i)if(h.hasOwnProperty(d)){var v=h[d],y=s(v),b=f[d],m=s(b);if(u(v)&&u(b)&&!y&&!m){r[n]=v,o[n]=b,n+=1;continue t}p>c&&(h[d]=b)}else h[d]=f[d]}n-=1}return t},e.exports=r},{100:100,143:143,40:40,58:58,90:90}],55:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(54),i=t(56);r.prototype.get=i.prototype.get,r.prototype.removeRequest=i.prototype.removeRequest,r.prototype.set=o.prototype.set,r.prototype.call=o.prototype.call,e.exports=r},{54:54,56:56}],56:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(57),i=t(52);r.prototype={setScheduler:function(t){this.scheduler=t},get:function(t,e,n){function r(){v||(--h,0===h&&n())}var s,u,a,c=this,p=[],h=0,f=c._requests,l=e,d=t,v=!1;for(s=0,u=f.length;u>s;++s)if(a=f[s],a.type===o.GetRequest){if(a.sent){var y=a.add(d,l,r);y[0]&&(d=y[1],l=y[2],p[p.length]=y[3],++h)}else a.batch(d,l,r),l=[],d=[],++h;if(!l.length)break}if(l.length){a=new i(c.scheduler,c),f[f.length]=a,++h;var b=a.batch(d,l,r);p[p.length]=b}return function(){if(!v&&0!==h){v=!0;for(var t=p.length,e=0;t>e;++e)p[e]()}}},removeRequest:function(t){for(var e=this._requests,n=e.length;--n>=0;)if(e[n].id===t.id){e.splice(n,1);break}}},e.exports=r},{52:52,57:57}],57:[function(t,e,n){e.exports={GetRequest:"GET"}},{}],58:[function(t,e,n){function r(){s.call(this)}var o=t(159),i=o.Observer,s=t(53),u=t(83),a=t(76),c=t(78),p=new Array(0);r.create=function(t,e){var n=new r;return n.model=t,n.jsonGraphEnvelope=e,n},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.method="set",r.prototype.insertPath=function(){return!1},r.prototype.removePath=function(){return 0},r.prototype.getSourceArgs=function(){return this.jsonGraphEnvelope},r.prototype.getSourceObserver=function(t){var e=this.model,n=e._path,r=this.jsonGraphEnvelope.paths,o=e._root,h=o.errorSelector,f=o.comparator;return s.prototype.getSourceObserver.call(this,i.create(function(o){e._path=p;var i=a(e,[{paths:r,jsonGraph:o.jsonGraph}],null,h,f);o.paths=i[1],e._path=n,t.onNext(o)},function(o){e._path=p,c(e,u(r,function(t){return{path:t,value:o}}),null,h,f),e._path=n,t.onError(o)},function(){t.onCompleted()}))},e.exports=r},{159:159,53:53,76:76,78:78,83:83}],59:[function(t,e,n){var r=t(143).hasIntersection,o=t(84);e.exports=function(t,e,n){for(var i=[],s=[],u=[],a=-1,c=-1,p=!1,h=0,f=e.length;f>h;++h){var l=e[h],d=n[l.length];d&&r(d,l,0)?(!p&&h>0&&(s=o(t,0,h),i=o(e,0,h)),u[++a]=t[h],p=!0):p&&(i[++c]=l,s[c]=t[h])}return p?[u,i,s]:null}},{143:143,84:84}],60:[function(t,e,n){var r=t(143),o=r.toTree,i=r.toPaths;e.exports=function(t,e,n){if(0===t._count)return void t.requestQueue.removeRequest(t);t.sent=!0,t.scheduled=!1;for(var r=t._pathMap,s=Object.keys(e),u=0,a=s.length;a>u;++u)for(var c=e[u],p=0,h=c.length;h>p;++p){var f=c[p],l=f.length;if(r[l]){var d=r[l];d[d.length]=f}else r[l]=[f]}for(var v=Object.keys(r),y=0,b=v.length;b>y;++y){var m=v[y];r[m]=o(r[m])}var g,w=t._collasped=i(r);t.requestQueue.model._source.get(w).subscribe(function(t){g=t},function(t){n(t,g)},function(){n(null,g)})}},{143:143}],61:[function(t,e,n){function r(t){u.call(this,t||i)}function o(t){return s.Observable.defer(function(){return t})}function i(t){function e(t){function e(t,e){if(Boolean(e.invalidated))t.invalidations.push(t.localThisPath.concat(e.path));else{var n=e.path,r=e.value;Boolean(r)&&"object"==typeof r&&r.$type===f?t.references.push({path:i(n),value:e.value}):t.values.push({path:i(n),value:e.value})}return t}function n(t){var e=t.values.concat(t.references);return e.length>0?o(g.set.apply(g,e)._toJSONG()).map(function(e){return{results:t,envelope:e}}):u["return"]({results:t,envelope:{jsonGraph:{},paths:[]}})}function r(t){var e,n=t.envelope,r=t.results,c=r.values,p=r.references,h=r.invalidations,f=c.map(a).map(i),l=p.reduce(s,[]),d=b.map(i),v=l.concat(d);return e=v.length>0?o(m.get.apply(m,f.concat(v))._toJSONG()):u["return"](n),e.doAction(function(t){t.invalidated=h})}function s(t,e){var n=e.path;return t.push.apply(t,y.map(function(t){return n.concat(t)})),t}function a(t){return t.path}var c=t&&t.localFn;if("function"==typeof c){var p=t.model,h=p._path,l=c.apply(p,v).reduce(e,{values:[],references:[],invalidations:[],localThisPath:h}).flatMap(n).flatMap(r);return u["return"](l)}return u.empty()}function n(t){function e(t){var e=t.invalidated;return e&&e.length&&m.invalidate.apply(m,e),t}return t&&"object"==typeof t?s.Observable.defer(function(){ var e;try{e=t.call(x,v,y,b)}catch(n){e=u["throw"](new p(n))}return e}).map(e):u.empty()}function r(t){return o(g.set(t)).reduce(function(t){return t},null).map(function(){return{invalidated:t.invalidated,paths:t.paths.map(function(t){return t.slice(w.length)})}})}function i(t){return _.concat(t)}var c=this.args,l=this.model,d=h.fromPath(c[0]),v=c[1]||[],y=(c[2]||[]).map(h.fromPath),b=(c[3]||[]).map(h.fromPath),m=l._clone({_path:[]}),g=m.withoutDataSource(),w=l._path,x=w.concat(d),_=x.slice(0,-1),S=o(l.withoutDataSource().get(d)).map(function(t){for(var e=t.json,n=-1,r=d.length;e&&++n0){var p="_"+n+a+"AsJSON",h=e[p];h(e,c)}}return t.onCompleted(),s.empty}var i=t(159),s=i.Disposable,u=t(62);r.create=u.create,r.prototype=Object.create(u.prototype),r.prototype.method="invalidate",r.prototype.constructor=r,e.exports=r},{159:159,62:62}],64:[function(t,e,n){function r(t){this._subscribe=t}function o(t){var e=this.model,n=new this.type;return n.model=e,n.args=this.args,n.outputFormat=t.outputFormat||"AsPathMap",n.isProgressive=t.isProgressive||!1,n.subscribeCount=0,n.subscribeLimit=t.retryLimit||10,n.initialize().invokeSourceRequest(e).ensureCollect(e).subscribe(t)}var i=t(32),s=t(159)&&t(158),u=s.Observable,a=t(84),c=t(105),p={outputFormat:{value:"AsJSONG"}},h={isProgressive:{value:!0}};r.create=function(t,e){var n=new r(o);return n.args=e,n.type=this,n.model=t,n},r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype._mixin=function(){var t=this,e=a(arguments);return new t.constructor(function(n){return t.subscribe(e.reduce(function(t,e){return Object.create(t,e)},n))})},r.prototype._toJSONG=function(){return this._mixin(p)},r.prototype.progressively=function(){return this._mixin(h)},r.prototype.subscribe=function(t,e,n){var r=t;r&&"object"==typeof r||(r={onNext:t||c,onError:e||c,onCompleted:n||c});var o=this._subscribe(r);switch(typeof o){case"function":return{dispose:o};case"object":return o||{dispose:c};default:return{dispose:c}}},r.prototype.then=function(t,e){var n=this;return new i.Promise(function(t,e){var r,o=!1;n.toArray().subscribe(function(t){r=t.length<=1?t[0]:t},function(t){o=!0,e(t)},function(){o===!1&&t(r)})}).then(t,e)},e.exports=r},{105:105,158:158,159:159,32:32,84:84}],65:[function(t,e,n){function r(t){l.call(this,t||o)}function o(t){return this.isCompleted?s.call(this,t):i.call(this,t)}function i(t){if(this.subscribeCount++>this.subscribeLimit)return t.onError("Loop kill switch thrown."),h.empty;for(var e=[],n=[],r=this.model,o=this.isMaster,i=r._root,c=this.outputFormat,p=i.errorSelector,f=this.method,l=this.groups,d=-1,y=l.length;++d0){var w="_"+f+m+c,x=r[w],_=x(r,g,null,p);n.push.apply(n,_[1]),"PathValues"===m?e.push.apply(e,g.map(u)):"JSONGs"===m?e.push.apply(e,v(g,a)):e.push.apply(e,_[0])}}return this.requestedPaths=e,o?(this.isCompleted=!0,s.call(this,t)):void t.onError({method:f,optimizedPaths:n,invokeSourceRequest:!0})}function s(t){var e=new f(this.model,this.requestedPaths);return"AsJSONG"===this.outputFormat&&(e=e._toJSONG()),this.isProgressive&&(e=e.progressively()),e.subscribe(t)}function u(t){return t.path}function a(t){return t.paths}var c=t(159),p=c.Observable,h=c.Disposable,f=t(67),l=t(62),d=t(9),v=t(82),y=new Array(0);r.create=l.create,r.prototype=Object.create(l.prototype),r.prototype.method="set",r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){var e=this,n=this["catch"](function(r){var o;if(r&&r.invokeSourceRequest===!0){var i={},s=t._path,u=r.optimizedPaths;t._path=y,t._getPathValuesAsJSONG(t._materialize().withoutDataSource(),u,[i]),t._path=s,o=t._request.set(i)["do"](function(t){e.isCompleted=u.length===t.paths.length},function(){e.isCompleted=!0}).materialize().flatMap(function(t){if("C"===t.kind)return p.empty();if("E"===t.kind){var e=t.exception;if(d.is(e))return p["throw"](t.exception)}return n})}else o=p["throw"](r);return o});return new this.constructor(function(t){return n.subscribe(t)})},e.exports=r},{159:159,62:62,67:67,82:82,9:9}],66:[function(t,e,n){var r=function(t){this.disposed=!1,this.currentDisposable=t};r.prototype={dispose:function(){if(!this.disposed&&this.currentDisposable){this.disposed=!0;var t=this.currentDisposable;t.dispose?t.dispose():t()}}},e.exports=r},{}],67:[function(t,e,n){var r=t(64),o=t(68),i=t(69),s={dispose:function(){}},u=t(159).Observable,a=e.exports=function(t,e,n,r){this.model=t,this.currentRemainingPaths=e,this.isJSONGraph=n||!1,this.isProgressive=r||!1};a.prototype=Object.create(u.prototype),a.prototype.subscribe=r.prototype.subscribe,a.prototype.then=r.prototype.then,a.prototype._toJSONG=function(){return new a(this.model,this.currentRemainingPaths,!0,this.isProgressive)},a.prototype.progressively=function(){return new a(this.model,this.currentRemainingPaths,this.isJSONGraph,!0)},a.prototype._subscribe=function(t){var e=[{}],n=[],r=t.isJSONG=this.isJSONGraph,u=this.isProgressive,a=o(this.model,this.currentRemainingPaths,t,u,r,e,n);return a?i(this,this.model,a,t,e,n,1):s}},{159:159,64:64,68:68,69:69}],68:[function(t,e,n){var r=t(19),o=r.getWithPathsAsJSONGraph,i=r.getWithPathsAsPathMap;e.exports=function(t,e,n,r,s,u,a){var c;if(c=s?o(t,e,u):i(t,e,u),c.criticalError)return n.onError(c.criticalError),null;var p=c.hasValue,h=!c.requestedMissingPaths||!t._source,f=u[0].json||u[0].jsonGraph;if(c.errors)for(var l=c.errors,d=a.length,v=0,y=l.length;y>v;++v,++d)a[d]=l[v];if(p&&r||f&&h)try{++t._root.syncRefCount,n.onNext(u[0])}catch(b){throw b}finally{--t._root.syncRefCount}return h?(a.length?n.onError(a):n.onCompleted(),null):c}},{19:19}],69:[function(t,e,n){var r=t(68),o=t(10),i=t(30).fastCat,s=t(49),u=t(88),a=t(66),c=t(46);e.exports=function p(t,e,n,h,f,l,d){if(10===d)throw new o;var v=e._request,y=n.requestedMissingPaths,b=n.optimizedMissingPaths,m=new a,g=[],w=e._path;if(w.length)for(var x=0,_=y.length;_>x;++x)g[x]=i(w,y[x]);else g=y;var S=v.get(g,b,function(){var n=r(e,y,h,t.isProgressive,t.isJSONGraph,f,l);if(n)m.currentDisposable=p(t,e,n,h,f,l,d+1);else{var o=e._root,i=o.cache,a=i[c];s(o,o.expired,u(i),e._maxSize,e._collectRatio,a)}});return m.currentDisposable=S,m}},{10:10,30:30,46:46,49:49,66:66,68:68,88:88}],70:[function(t,e,n){var r=t(67);e.exports=function(t){return new r(this,t)}},{67:67}],71:[function(t,e,n){var r=t(134),o=t(64),i=t(72),s=t(116),u=t(67);e.exports=function(){var t=s(arguments,i,"get");if(t!==!0)return new o(function(e){e.onError(t)});var e=r.fromPathsOrPathValues(arguments);return new u(this,e)}},{116:116,134:134,64:64,67:67,72:72}],72:[function(t,e,n){e.exports={path:!0,pathSyntax:!0}},{}],73:[function(t,e,n){function r(){}var o=t(123),i=t(159),s=i.Disposable;r.prototype.schedule=function(t){return o(t),s.empty},r.prototype.scheduleWithState=function(t,e){var n=this;return o(function(){e(n,t)}),s.empty},e.exports=r},{123:123,159:159}],74:[function(t,e,n){function r(){}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){return t(),i.empty},r.prototype.scheduleWithState=function(t,e){return e(this,t),i.empty},e.exports=r},{159:159}],75:[function(t,e,n){function r(t){this.delay=t}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){var e=setTimeout(t,this.delay);return i.create(function(){void 0!==e&&(clearTimeout(e),e=void 0)})},r.prototype.scheduleWithState=function(t,e){var n=this,r=setTimeout(function(){e(n,t)},this.delay);return i.create(function(){void 0!==r&&(clearTimeout(r),r=void 0)})},e.exports=r},{159:159}],76:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,d,v,y,b,g,w){for(var x={},_=ex,k=i(t,E,e,n,C,r,A,N,!0,o,s,c,f,v,m,g);if(e=k[0],y(e))return s.index=x,k;E=k[1],r=k[2],C=k[3]}while(x++=x)break;h.index=_}}function o(t,e,n,r,o,s,u,c,f,v){var y=n.value;if(o.splice(0,o.length),o.push.apply(o,y),x(n))return o.index=y.length,E(n,u,c),[void 0,e];m(c,n);var b=n,g=e;if(n=n[h],null!=n)g=n[p]||e,o.index=y.length;else{var w=0,_=y.length-1;g=n=e;do{var C=y[w],A=_>w,N=i(e,g,n,C,t,A,!0,r,o,s,u,c,f,v);if(n=N[0],S(n))return o.index=w,N;g=N[1]}while(w++<_);if(o.index=w,b[h]!==n){var k=n[d]||0;n[d]=k+1,n[a+k]=b,b[h]=n,b[l]=k}}return[n,g]}function i(t,e,n,r,i,s,a,c,p,h,f,l,d,y){for(var b=n.$type;b===v;){var m=o(i,t,n,c,p,h,f,l,d,y);if(n=m[0],S(n))return m;e=m[1],b=n&&n.$type}if(void 0!==b)return[n,e];if(null==r){if(s)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[u])}else e=n,n=e[r];return n=A(e,n,r,i,s,a,c,p,h,f,l,d,y),[n,e]}function s(t){if(w(t)&&!t.$type){var e=[],n=0;b(t)&&(e[n++]="length");for(var r in t)r[0]!==c&&"$"!==r[0]&&g(t,r)&&(e[n++]=r);return e}}var u=t(36),a=t(43),c=t(40),p=t(39),h=t(33),f=t(46),l=t(42),d=t(44),v=t(120),y=t(13),b=Array.isArray,m=t(50),g=t(91),w=t(100),x=t(95),_=t(96),S=t(102),E=t(86),C=t(92),A=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,c=C(),h=t._path,l=s.cache,d=h.length?y(t,h).value:l,v=d[p]||l,b=l[f],m=[],g=[],w=[],x=h.length,S=-1,E=e.length;++SS,N=i(e,_,n,C,t,A,!0,r,o,s,p,l,d,b);if(n=N[0],m(n))return o.index=S,N;_=N[1]}while(S++i&&(i=0),n>0&&i>n&&(i=n);for(var s=new Array(i);++oq)return}if(k&&j&&!O)return d(y(e,n,t,g,E),t,g);if(O||!j){if(O===s&&h(A)&&(n=A(m(w,g),n)),O&&e===n)null==e[o]&&(e=l(e,k,e.value),t=b(t,-e.$size,E,_),e=d(e,t,g,_));else{var R=!0;!k&&P||(R=a(n)-1);return t}},{39:39,43:43,44:44,46:46}],115:[function(t,e,n){var r=t(36),o=t(46),i=t(39),s=t(108),u=t(114);e.exports=function(t,e,n,a){var c=t;do{var p=c[i],h=c.$size=(c.$size||0)-e;0>=h&&null!=p?s(c,p,c[r],n):c[o]!==a&&u(c,a),c=p}while(c);return t}},{108:108,114:114,36:36,39:39,46:46}],116:[function(t,e,n){var r=Array.isArray,o=t(101),i=t(99),s=t(98),u=t(134);e.exports=function(t,e,n){for(var a=0,c=t.length;c>a;++a){var p=t[a],h=!1;if(r(p)&&e.path?h=!0:"string"==typeof p&&e.pathSyntax?h=!0:o(p)&&e.pathValue?(p.path=u.fromPath(p.path),h=!0):i(p)&&e.jsonGraph?h=!0:s(p)&&e.json?h=!0:"function"==typeof p&&a+1===c&&e.selector&&(h=!0),!h)return new Error("Unrecognized argument "+typeof p+" ["+String(p)+"] to Model#"+n)}return!0}},{101:101,134:134,98:98,99:99}],117:[function(t,e,n){var r=t(130),o=r.atom,i=t(106),s=t(122),u=t(37),a=50,c=t(85),p=Array.isArray,h=t(88),f=t(87);e.exports=function(t,e,n){var r=0,l=t,d=e;if(d?(l=c(l),r=h(l),l.$type=d):(l=o(n),d=l.$type,l[u]=!0),null==n)r=a+1;else if(null==r||0>=r)switch(typeof n){case"object":r=p(n)?a+n.length:a+1;break;case"string":r=a+n.length;break;default:r=a+1}var v=f(l);return"number"==typeof v&&s>v&&(l.$expires=i()+-1*v),l.$size=r,l}},{106:106,122:122,130:130,37:37,85:85,87:87,88:88}],118:[function(t,e,n){e.exports="atom"},{}],119:[function(t,e,n){e.exports="error"},{}],120:[function(t,e,n){e.exports="ref"},{}],121:[function(t,e,n){e.exports=1},{}],122:[function(t,e,n){e.exports=0},{}],123:[function(t,e,n){"use strict";function r(){if(a.length)throw a.shift()}function o(t){var e;e=u.length?u.pop():new i,e.task=t,s(e)}function i(){this.task=null}var s=t(124),u=[],a=[],c=s.makeRequestCallFromTimer(r);e.exports=o,i.prototype.call=function(){try{this.task.call()}catch(t){o.onerror?o.onerror(t):(a.push(t),c())}finally{this.task=null,u[u.length]=this}}},{124:124}],124:[function(t,e,n){(function(t){"use strict";function n(t){u.length||(s(),a=!0),u[u.length]=t}function r(){for(;cp){for(var e=0,n=u.length-c;n>e;e++)u[e]=u[e+c];u.length-=c,c=0}}u.length=0,c=0,a=!1}function o(t){var e=1,n=new h(t),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){e=-e,r.data=e}}function i(t){return function(){function e(){clearTimeout(n),clearInterval(r),t()}var n=setTimeout(e,0),r=setInterval(e,50)}}e.exports=n;var s,u=[],a=!1,c=0,p=1024,h=t.MutationObserver||t.WebKitMutationObserver;s="function"==typeof h?o(r):i(r),n.requestFlush=s,n.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],125:[function(t,e,n){"use strict";function r(t,e){var n;for(n in e)t[n]=e[n];return t}function o(t,e){if(this._jsongUrl=t,"number"==typeof e){var n={timeout:e};e=n}this._config=r({timeout:15e3,headers:{}},e||{})}var i=t(129),s=t(126);Array.isArray;o.prototype={constructor:o,buildQueryObject:s,get:function(t){var e="GET",n=this.buildQueryObject(this._jsongUrl,e,{paths:t,method:"get"}),o=r(n,this._config),s=this;return i(e,o,s)},set:function(t){var e="POST",n=this.buildQueryObject(this._jsongUrl,e,{jsonGraph:t,method:"set"}),o=r(n,this._config);o.headers["Content-Type"]="application/x-www-form-urlencoded";var s=this;return i(e,o,s)},call:function(t,e,n,o){e=e||[],n=n||[],o=o||[];var s="POST",u=[];u.push("method=call"),u.push("callPath="+encodeURIComponent(JSON.stringify(t))),u.push("arguments="+encodeURIComponent(JSON.stringify(e))),u.push("pathSuffixes="+encodeURIComponent(JSON.stringify(n))),u.push("paths="+encodeURIComponent(JSON.stringify(o)));var a=this.buildQueryObject(this._jsongUrl,s,u.join("&")),c=r(a,this._config);c.headers["Content-Type"]="application/x-www-form-urlencoded";var p=this;return i(s,c,p)}},o.XMLHttpSource=o,o["default"]=o,e.exports=o},{126:126,129:129}],126:[function(t,e,n){"use strict";e.exports=function(t,e,n){var r,o=[],i={url:t},s=-1!==t.indexOf("?"),u=s?"&":"?";return"string"==typeof n?o.push(n):(r=Object.keys(n),r.forEach(function(t){var e="object"==typeof n[t]?JSON.stringify(n[t]):n[t];o.push(t+"="+encodeURIComponent(e))})),"GET"===e?i.url+=u+o.join("&"):i.data=o.join("&"),i}},{}],127:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e=new t.XMLHttpRequest;if("withCredentials"in e)return e;if(t.XDomainRequest)return new XDomainRequest;throw new Error("CORS is not supported by your browser")}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],128:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e,n,r;if(t.XMLHttpRequest)return new t.XMLHttpRequest;try{for(n=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],r=0;3>r;r++)try{if(e=n[r],new t.ActiveXObject(e))break}catch(o){}return new t.ActiveXObject(e)}catch(o){throw new Error("XMLHttpRequest is not supported by your browser")}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],129:[function(t,e,n){"use strict";function r(){}function o(t,e,n){return r.create(function(r){var o,i,h,f,l,d={method:t||"GET",crossDomain:!1,async:!0,headers:{},responseType:"json"};for(l in e)p.call(e,l)&&(d[l]=e[l]);d.crossDomain||d.headers["X-Requested-With"]||(d.headers["X-Requested-With"]="XMLHttpRequest"),null!=n.onBeforeRequest&&n.onBeforeRequest(d);try{o=d.crossDomain?c():a()}catch(v){r.onError(v)}try{d.user?o.open(d.method,d.url,d.async,d.user,d.password):o.open(d.method,d.url,d.async),o.timeout=d.timeout,o.withCredentials=d.withCredentials!==!1,h=d.headers;for(f in h)p.call(h,f)&&o.setRequestHeader(f,h[f]);if(d.responseType)try{o.responseType=d.responseType}catch(y){if("json"!==d.responseType)throw y}o.onreadystatechange=function(t){4===o.readyState&&(i||(i=!0,s(r,o,t)))},o.ontimeout=function(t){i||(i=!0,u(r,o,"timeout error",t))},o.send(d.data)}catch(y){r.onError(y)}return function(){i||4===o.readyState||(i=!0,o.abort())}})}function i(t,e,n){n||(n=new Error(e)),t.onError(n)}function s(t,e,n){var r,o;if(e&&t){o=e.responseType,r="response"in e?e.response:e.responseText;var s=1223===e.status?204:e.status;if(s>=200&&399>=s){try{"json"!==o&&(r=JSON.parse(r||"")),"string"==typeof r&&(r=JSON.parse(r||""))}catch(n){i(t,"invalid json",n)}return t.onNext(r),void t.onCompleted()}return 401===s||403===s||407===s?i(t,r):410===s?i(t,r):408===s||504===s?i(t,r):i(t,r||"Response code "+s)}}function u(t,e,n,r){i(t,n||e.statusText||"request error",r)}var a=t(128),c=t(127),p=Object.prototype.hasOwnProperty,h=function(){};r.create=function(t){var e=new r;return e.subscribe=function(e,n,r){var o,i;return o="function"==typeof e?{onNext:e,onError:n||h,onCompleted:r||h}:e,i=t(o),"function"==typeof i?{dispose:i}:i},e},e.exports=o},{127:127,128:128}],130:[function(t,e,n){function r(t,e,n){var r=Object.create(null);if(null!=n){for(var o in n)r[o]=n[o];return r.$type=t,r.value=e,r}return{$type:t,value:e}}var o=t(134);e.exports={ref:function(t,e){return r("ref",o.fromPath(t),e)},atom:function(t,e){return r("atom",t,e)},undefined:function(){return r("atom")},error:function(t,e){return r("error",t,e)},pathValue:function(t,e){return{path:o.fromPath(t),value:e}},pathInvalidation:function(t){return{path:o.fromPath(t),invalidated:!0}}}},{134:134}],131:[function(t,e,n){e.exports={integers:"integers",ranges:"ranges",keys:"keys"}},{}],132:[function(t,e,n){var r={token:"token",dotSeparator:".",commaSeparator:",",openingBracket:"[",closingBracket:"]",openingBrace:"{",closingBrace:"}",escape:"\\",space:" ",colon:":",quote:"quote",unknown:"unknown"};e.exports=r},{}],133:[function(t,e,n){e.exports={indexer:{nested:"Indexers cannot be nested.",needQuotes:"unquoted indexers must be numeric.",empty:"cannot have empty indexers.",leadingDot:"Indexers cannot have leading dots.",leadingComma:"Indexers cannot have leading comma.",requiresComma:"Indexers require commas between indexer args.",routedTokens:"Only one token can be used per indexer when specifying routed tokens."},range:{precedingNaN:"ranges must be preceded by numbers.",suceedingNaN:"ranges must be suceeded by numbers."},routed:{invalid:"Invalid routed token. only integers|ranges|keys are supported."},quote:{empty:"cannot have empty quoted keys.",illegalEscape:"Invalid escape character. Only quotes are escapable."},unexpectedToken:"Unexpected token.",invalidIdentifier:"Invalid Identifier.",invalidPath:"Please provide a valid path.",throwError:function(t,e,n){if(n)throw t+" -- "+e.parseString+" with next token: "+n;throw t+" -- "+e.parseString}}},{}],134:[function(t,e,n){var r=t(140),o=t(135),i=t(131),s=function(t,e){return o(new r(t,e))};e.exports=s,s.fromPathsOrPathValues=function(t,e){if(!t)return[];for(var n=[],r=0,o=t.length;o>r;r++)"string"==typeof t[r]?n[r]=s(t[r],e):"string"==typeof t[r].path?n[r]={path:s(t[r].path,e),value:t[r].value}:n[r]=t[r];return n},s.fromPath=function(t,e){return t?"string"==typeof t?s(t,e):t:[]},s.RoutedTokens=i},{131:131,135:135,140:140}],135:[function(t,e,n){var r=t(132),o=t(133),i=t(136);e.exports=function(t){for(var e=t.next(),n={},s=[];!e.done;){switch(e.type){case r.token:var u=+e.token[0];isNaN(u)||o.throwError(o.invalidIdentifier,t),s[s.length]=e.token;break;case r.dotSeparator:0===s.length&&o.throwError(o.unexpectedToken,t);break;case r.space:break;case r.openingBracket:i(t,e,n,s);break;default:o.throwError(o.unexpectedToken,t)}e=t.next()}return 0===s.length&&o.throwError(o.invalidPath,t),s}},{132:132,133:133,136:136}],136:[function(t,e,n){var r=t(132),o=t(133),i=o.indexer,s=t(138),u=t(137),a=t(139);e.exports=function(t,e,n,c){var p=t.next(),h=!1,f=1,l=!1;for(n.indexer=[];!p.done;){switch(p.type){case r.token:case r.quote:n.indexer.length===f&&o.throwError(i.requiresComma,t)}switch(p.type){case r.openingBrace:l=!0,a(t,p,n,c);break;case r.token:var d=+p.token;isNaN(d)&&o.throwError(i.needQuotes,t),n.indexer[n.indexer.length]=d;break;case r.dotSeparator:n.indexer.length||o.throwError(i.leadingDot,t),s(t,p,n,c); @@ -3276,27 +3461,29 @@ if(!this.isDisposed){this.isDisposed=!0;for(var t=this.disposables.length,e=new return new Sn(this)},qe.onErrorResumeNext=function(t){if(!t)throw new Error("Second observable is required");return En([this,t])};var En=We.onErrorResumeNext=function(){var t=[];if(Array.isArray(arguments[0]))t=arguments[0];else for(var e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return new qn(function(e){var n=0,r=new le,o=xe.scheduleRecursive(function(o){var i,s;nn;n++)e[n]=arguments[n];var r=e.pop(),o=this;return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){for(var n=e.length,i=g(n,W),s=!1,u=new Array(n),a=new Array(n+1),c=0;n>c;c++)!function(n){var r=e[n],o=new fe;ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(t){u[n]=t,i[n]=!0,s=i.every(nt)},function(e){t.onError(e)},et)),a[n]=o}(c);var p=new fe;return p.setDisposable(o.subscribe(function(e){var n=[e].concat(u);if(s){var o=x(r).apply(null,n);return o===ne?t.onError(o.e):void t.onNext(o)}},function(e){t.onError(e)},function(){t.onCompleted()})),a[n]=p,new ie(a)},this)},qe.zip=function(){if(Array.isArray(arguments[0]))return z.apply(this,arguments);for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=this,o=e.pop();return e.unshift(r),new qn(function(t){for(var n=e.length,i=g(n,G),s=g(n,W),u=new Array(n),a=0;n>a;a++)!function(n){var a=e[n],c=new fe;ut(a)&&(a=Xe(a)),c.setDisposable(a.subscribe(function(e){if(i[n].push(e),i.every(function(t){return t.length>0})){var u=i.map(function(t){return t.shift()}),a=x(o).apply(r,u);if(a===ne)return t.onError(a.e);t.onNext(a)}else s.filter(function(t,e){return e!==n}).every(nt)&&t.onCompleted()},function(e){t.onError(e)},function(){s[n]=!0,s.every(nt)&&t.onCompleted()})),u[n]=c}(a);return new ie(u)},r)},We.zip=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.shift();return r.zip.apply(r,e)},We.zipArray=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{var e=arguments.length;t=new Array(e);for(var n=0;e>n;n++)t[n]=arguments[n]}return new qn(function(e){for(var n=t.length,r=g(n,J),o=g(n,W),i=new Array(n),s=0;n>s;s++)!function(n){i[n]=new fe,i[n].setDisposable(t[n].subscribe(function(t){if(r[n].push(t),r.every(function(t){return t.length>0})){var i=r.map(function(t){return t.shift()});e.onNext(i)}else if(o.filter(function(t,e){return e!==n}).every(nt))return e.onCompleted()},function(t){e.onError(t)},function(){o[n]=!0,o.every(nt)&&e.onCompleted()}))}(s);return new ie(i)})},qe.asObservable=function(){var t=this;return new qn(function(e){return t.subscribe(e)},t)},qe.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},qe.dematerialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){return t.accept(e)},function(t){e.onError(t)},function(){e.onCompleted()})},this)},qe.distinctUntilChanged=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o,i=!1;return n.subscribe(function(n){var s=n;if(t&&(s=x(t)(n),s===ne))return r.onError(s.e);if(i){var u=x(e)(o,s);if(u===ne)return r.onError(u.e)}i&&u||(i=!0,o=s,r.onNext(n))},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Nn=function(t){function e(e,n,r,o){this.source=e,this.t=!n||at(n)?De(n||et,r||et,o||et):n,t.call(this)}function n(t,e){this.o=t,this.t=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.t))},n.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.t.onNext).call(this.t,t);e===ne&&this.o.onError(e.e),this.o.onNext(t)}},n.prototype.onError=function(t){if(!this.isStopped){this.isStopped=!0;var e=x(this.t.onError).call(this.t,t);if(e===ne)return this.o.onError(e.e);this.o.onError(t)}},n.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=x(this.t.onCompleted).call(this.t);if(t===ne)return this.o.onError(t.e);this.o.onCompleted()}},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe["do"]=qe.tap=qe.doAction=function(t,e,n){return new Nn(this,t,e,n)},qe.doOnNext=qe.tapOnNext=function(t,e){return this.tap("undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnError=qe.tapOnError=function(t,e){return this.tap(et,"undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnCompleted=qe.tapOnCompleted=function(t,e){return this.tap(et,null,"undefined"!=typeof e?function(){t.call(e)}:t)},qe["finally"]=qe.ensure=function(t){var e=this;return new qn(function(n){var r;try{r=e.subscribe(n)}catch(o){throw t(),o}return ae(function(){try{r.dispose()}catch(e){throw e}finally{t()}})},this)},qe.finallyAction=function(t){return this.ensure(t)};var kn=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=et,n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},e}(ze);qe.ignoreElements=function(){return new kn(this)},qe.materialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){e.onNext(ke(t))},function(t){e.onNext(Oe(t)),e.onCompleted()},function(){e.onNext(Pe()),e.onCompleted()})},t)},qe.repeat=function(t){return Be(this,t).concat()},qe.retry=function(t){return Be(this,t).catchError()},qe.retryWhen=function(t){return Be(this).catchErrorWhen(t)};var On=function(t){function e(e,n,r,o){this.source=e,this.accumulator=n,this.hasSeed=r,this.seed=o,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new I(t,this))},e}(ze);I.prototype.onNext=function(t){if(!this.isStopped){!this.hasValue&&(this.hasValue=!0);try{this.hasAccumulation?this.accumulation=this.accumulator(this.accumulation,t):(this.accumulation=this.hasSeed?this.accumulator(this.seed,t):t,this.hasAccumulation=!0)}catch(e){return this.observer.onError(e)}this.observer.onNext(this.accumulation)}},I.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.observer.onError(t))},I.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,!this.hasValue&&this.hasSeed&&this.observer.onNext(this.seed),this.observer.onCompleted())},I.prototype.dispose=function(){this.isStopped=!0},I.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},qe.scan=function(){var t,e,n=!1;return 2===arguments.length?(n=!0,t=arguments[0],e=arguments[1]):e=arguments[0],new On(this,e,n,t)},qe.skipLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},function(t){n.onError(t)},function(){n.onCompleted()})},e)},qe.startWith=function(){var t,e=0;arguments.length&&me(arguments[0])?(t=arguments[0],e=1):t=xe;for(var n=[],r=e,o=arguments.length;o>r;r++)n.push(arguments[r]);return Ue([on(n,t),this]).concat()},qe.takeLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){for(;r.length>0;)n.onNext(r.shift());n.onCompleted()})},e)},qe.takeLastBuffer=function(t){var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},qe.windowWithCount=function(t,e){var n=this;if(+t||(t=0),Math.abs(t)===1/0&&(t=0),0>=t)throw new yt;if(null==e&&(e=t),+e||(e=0),Math.abs(e)===1/0&&(e=0),0>=e)throw new yt;return new qn(function(r){function o(){var t=new Tn;a.push(t),r.onNext(ee(t,s))}var i=new fe,s=new de(i),u=0,a=[];return o(),i.setDisposable(n.subscribe(function(n){for(var r=0,i=a.length;i>r;r++)a[r].onNext(n);var s=u-t+1;s>=0&&s%e===0&&a.shift().onCompleted(),++u%e===0&&o()},function(t){for(;a.length>0;)a.shift().onError(t);r.onError(t)},function(){for(;a.length>0;)a.shift().onCompleted();r.onCompleted()})),s},n)},qe.selectConcat=qe.concatMap=function(t,e,n){return at(t)&&at(e)?this.concatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})}):at(t)?L(this,t,n):L(this,function(){return t})},qe.concatMapObserver=qe.selectConcatObserver=function(t,e,n,r){var o=this,i=At(t,r,2),s=At(e,r,1),u=At(n,r,0);return new qn(function(t){var e=0;return o.subscribe(function(n){var r;try{r=i(n,e++)}catch(o){return void t.onError(o)}ut(r)&&(r=Xe(r)),t.onNext(r)},function(e){var n;try{n=s(e)}catch(r){return void t.onError(r)}ut(n)&&(n=Xe(n)),t.onNext(n),t.onCompleted()},function(){var e;try{e=u()}catch(n){return void t.onError(n)}ut(e)&&(e=Xe(e)),t.onNext(e),t.onCompleted()})},this).concatAll()},qe.defaultIfEmpty=function(t){var e=this;return t===i&&(t=null),new qn(function(n){var r=!1;return e.subscribe(function(t){r=!0,n.onNext(t)},function(t){n.onError(t)},function(){!r&&n.onNext(t),n.onCompleted()})},e)},F.prototype.push=function(t){var e=-1===B(this.set,t,this.comparer);return e&&this.set.push(t),e},qe.distinct=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o=new F(e);return n.subscribe(function(e){var n=e;if(t)try{n=t(e)}catch(i){return void r.onError(i)}o.push(n)&&r.onNext(e)},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Pn=function(t){function e(e,n,r){this.source=e,this.selector=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return t.call(this,e.selector(n,r,o),r,o)}}function r(t,e,n){this.o=t,this.selector=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.internalMap=function(t,r){return new e(this.source,n(t,this),r)},e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.selector,this))},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.selector)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void this.o.onNext(e)}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.map=qe.select=function(t,e){var n="function"==typeof t?t:function(){return t};return this instanceof Pn?this.internalMap(n,e):new Pn(this,n,e)},qe.pluck=function(){var t=arguments,e=arguments.length;if(0===e)throw new Error("List of properties cannot be empty.");return this.map(function(n){for(var r=n,o=0;e>o;o++){var s=r[t[o]];if("undefined"==typeof s)return i;r=s}return r})},qe.flatMapObserver=qe.selectManyObserver=function(t,e,n,r){var o=this;return new qn(function(i){var s=0;return o.subscribe(function(e){var n;try{n=t.call(r,e,s++)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n)},function(t){var n;try{n=e.call(r,t)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n),i.onCompleted()},function(){var t;try{t=n.call(r)}catch(e){return void i.onError(e)}ut(t)&&(t=Xe(t)),i.onNext(t),i.onCompleted()})},o).mergeAll()},qe.selectMany=qe.flatMap=function(t,e,n){return at(t)&&at(e)?this.flatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})},n):at(t)?U(this,t,n):U(this,function(){return t})},qe.selectSwitch=qe.flatMapLatest=qe.switchMap=function(t,e){return this.select(t,e).switchLatest()};var jn=function(t){function e(e,n){this.source=e,this.skipCount=n,t.call(this)}function n(t,e){this.c=e,this.r=e,this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.skipCount))},n.prototype.onNext=function(t){this.isStopped||(this.r<=0?this.o.onNext(t):this.r--)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.skip=function(t){if(0>t)throw new yt;return new jn(this,t)},qe.skipWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!1;return n.subscribe(function(i){if(!o)try{o=!r(i,e++,n)}catch(s){return void t.onError(s)}o&&t.onNext(i)},function(e){t.onError(e)},function(){t.onCompleted()})},n)},qe.take=function(t,e){if(0>t)throw new yt;if(0===t)return Ye(e);var n=this;return new qn(function(e){var r=t;return n.subscribe(function(t){r-- >0&&(e.onNext(t),0>=r&&e.onCompleted())},function(t){e.onError(t)},function(){e.onCompleted()})},n)},qe.takeWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!0;return n.subscribe(function(i){if(o){try{o=r(i,e++,n)}catch(s){return void t.onError(s)}o?t.onNext(i):t.onCompleted()}},function(e){t.onError(e)},function(){t.onCompleted()})},n)};var Dn=function(t){function e(e,n,r){this.source=e,this.predicate=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return e.predicate(n,r,o)&&t.call(this,n,r,o)}}function r(t,e,n){this.o=t,this.predicate=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.predicate,this))},e.prototype.internalFilter=function(t,r){return new e(this.source,n(t,this),r)},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.predicate)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void(e&&this.o.onNext(t))}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.filter=qe.where=function(t,e){return this instanceof Dn?this.internalFilter(t,e):new Dn(this,t,e)},qe.transduce=function(t){function e(t){return{"@@transducer/init":function(){return t},"@@transducer/step":function(t,e){return t.onNext(e)},"@@transducer/result":function(t){return t.onCompleted()}}}var n=this;return new qn(function(r){var o=t(e(r));return n.subscribe(function(t){try{o["@@transducer/step"](r,t)}catch(e){r.onError(e)}},function(t){r.onError(t)},function(){o["@@transducer/result"](r)})},n)};var qn=tt.AnonymousObservable=function(t){function e(t){return t&&at(t.dispose)?t:at(t)?ae(t):ce}function n(t,n){var r=n[0],o=n[1],i=x(o)(r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(e,r){function o(t){var r=new Rn(t),o=[r,e];return _e.scheduleRequired()?_e.scheduleWithState(o,n):n(null,o),r}this.source=r,t.call(this,o)}return Zt(r,t),r}(We),Rn=function(t){function e(e){t.call(this),this.observer=e,this.m=new fe}Zt(e,t);var n=e.prototype;return n.next=function(t){var e=x(this.observer.onNext).call(this.observer,t);e===ne&&(this.dispose(),_(e.e))},n.error=function(t){var e=x(this.observer.onError).call(this.observer,t);this.dispose(),e===ne&&_(e.e)},n.completed=function(){var t=x(this.observer.onCompleted).call(this.observer);this.dispose(),t===ne&&_(t.e)},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Re),Mn=function(t,e){this.subject=t,this.observer=e};Mn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var Tn=tt.Subject=function(t){function e(t){return he(this),this.isStopped?this.hasError?(t.onError(this.error),ce):(t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(he(this),!this.isStopped){this.isStopped=!0;for(var t=0,e=u(this.observers),n=e.length;n>t;t++)e[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){if(he(this),!this.isStopped)for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),n.create=function(t,e){return new Vn(t,e)},n}(We),Vn=(tt.AsyncSubject=function(t){function e(t){return he(this),this.isStopped?(this.hasError?t.onError(this.error):this.hasValue?(t.onNext(this.value),t.onCompleted()):t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.hasValue=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je,{hasObservers:function(){return he(this),this.observers.length>0},onCompleted:function(){var t,e;if(he(this),!this.isStopped){this.isStopped=!0;var n=u(this.observers),e=n.length;if(this.hasValue)for(t=0;e>t;t++){var r=n[t];r.onNext(this.value),r.onCompleted()}else for(t=0;e>t;t++)n[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.hasError=!0,this.error=t;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){he(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),n}(We),tt.AnonymousSubject=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){this.observer=n,this.observable=r,t.call(this,e)}return Zt(n,t),te(n.prototype,je.prototype,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(We));"function"==typeof t&&"object"==typeof t.amd&&t.amd?(X.Rx=tt,t(function(){return tt})):Q&&K?Y?(K.exports=tt).Rx=tt:Q.Rx=tt:X.Rx=tt;var $n=f()}).call(this)}).call(this,e(150),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{150:150}]},{},[1])(1)}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],14:[function(require,module,exports){ +},{}],16:[function(require,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = require('min-document'); +var doccy; + if (typeof document !== 'undefined') { - module.exports = document; + doccy = document; } else { - var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; + doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } - - module.exports = doccy; } +module.exports = doccy; + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"min-document":2}],15:[function(require,module,exports){ +},{"min-document":4}],17:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -3382,7 +3569,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],16:[function(require,module,exports){ +},{}],18:[function(require,module,exports){ (function (global){ 'use strict'; @@ -3406,7 +3593,7 @@ function Individual(key, value) { }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],17:[function(require,module,exports){ +},{}],19:[function(require,module,exports){ 'use strict'; var Individual = require('./index.js'); @@ -3430,21 +3617,14 @@ function OneVersion(moduleName, version, defaultValue) { return Individual(key, defaultValue); } -},{"./index.js":16}],18:[function(require,module,exports){ +},{"./index.js":18}],20:[function(require,module,exports){ "use strict"; module.exports = function isObject(x) { return typeof x === "object" && x !== null; }; -},{}],19:[function(require,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -},{}],20:[function(require,module,exports){ +},{}],21:[function(require,module,exports){ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Geohash encoding/decoding and associated functions (c) Chris Veness 2014-2016 / MIT Licence */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -3690,7 +3870,7 @@ Geohash.neighbours = function(geohash) { /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js -},{}],21:[function(require,module,exports){ +},{}],22:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -3919,7 +4099,7 @@ var substr = 'ab'.substr(-1) === 'b' }).call(this,require('_process')) -},{"_process":4}],22:[function(require,module,exports){ +},{"_process":6}],23:[function(require,module,exports){ 'use strict'; module.exports = Pbf; @@ -3927,7 +4107,7 @@ module.exports = Pbf; var ieee754 = require('ieee754'); function Pbf(buf) { - this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0); + this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0); this.pos = 0; this.type = 0; this.length = this.buf.length; @@ -4539,7 +4719,7 @@ function writeUtf8(buf, str, pos) { return pos; } -},{"ieee754":15}],23:[function(require,module,exports){ +},{"ieee754":17}],24:[function(require,module,exports){ 'use strict'; module.exports = partialSort; @@ -4601,7 +4781,7 @@ function defaultCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0; } -},{}],24:[function(require,module,exports){ +},{}],25:[function(require,module,exports){ 'use strict'; module.exports = rbush; @@ -5164,7 +5344,7 @@ function multiSelect(arr, left, right, n, compare) { } } -},{"quickselect":23}],25:[function(require,module,exports){ +},{"quickselect":24}],26:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -5214,7 +5394,7 @@ var BehaviorSubject = (function (_super) { }(Subject_1.Subject)); exports.BehaviorSubject = BehaviorSubject; -},{"./Subject":33,"./util/ObjectUnsubscribedError":145}],26:[function(require,module,exports){ +},{"./Subject":34,"./util/ObjectUnsubscribedError":220}],27:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -5251,7 +5431,7 @@ var InnerSubscriber = (function (_super) { }(Subscriber_1.Subscriber)); exports.InnerSubscriber = InnerSubscriber; -},{"./Subscriber":35}],27:[function(require,module,exports){ +},{"./Subscriber":36}],28:[function(require,module,exports){ "use strict"; var Observable_1 = require('./Observable'); /** @@ -5269,10 +5449,10 @@ var Observable_1 = require('./Observable'); * @class Notification */ var Notification = (function () { - function Notification(kind, value, exception) { + function Notification(kind, value, error) { this.kind = kind; this.value = value; - this.exception = exception; + this.error = error; this.hasValue = kind === 'N'; } /** @@ -5285,7 +5465,7 @@ var Notification = (function () { case 'N': return observer.next && observer.next(this.value); case 'E': - return observer.error && observer.error(this.exception); + return observer.error && observer.error(this.error); case 'C': return observer.complete && observer.complete(); } @@ -5304,7 +5484,7 @@ var Notification = (function () { case 'N': return next && next(this.value); case 'E': - return error && error(this.exception); + return error && error(this.error); case 'C': return complete && complete(); } @@ -5337,7 +5517,7 @@ var Notification = (function () { case 'N': return Observable_1.Observable.of(this.value); case 'E': - return Observable_1.Observable.throw(this.exception); + return Observable_1.Observable.throw(this.error); case 'C': return Observable_1.Observable.empty(); } @@ -5354,12 +5534,12 @@ var Notification = (function () { if (typeof value !== 'undefined') { return new Notification('N', value); } - return this.undefinedValueNotification; + return Notification.undefinedValueNotification; }; /** * A shortcut to create a Notification instance of the type `error` from a * given error. - * @param {any} [err] The `error` exception. + * @param {any} [err] The `error` error. * @return {Notification} The "error" Notification representing the * argument. */ @@ -5371,7 +5551,7 @@ var Notification = (function () { * @return {Notification} The valueless "complete" Notification. */ Notification.createComplete = function () { - return this.completeNotification; + return Notification.completeNotification; }; Notification.completeNotification = new Notification('C'); Notification.undefinedValueNotification = new Notification('N', undefined); @@ -5379,13 +5559,14 @@ var Notification = (function () { }()); exports.Notification = Notification; -},{"./Observable":28}],28:[function(require,module,exports){ +},{"./Observable":29}],29:[function(require,module,exports){ "use strict"; var root_1 = require('./util/root'); var toSubscriber_1 = require('./util/toSubscriber'); var observable_1 = require('./symbol/observable'); +var pipe_1 = require('./util/pipe'); /** - * A representation of any set of values over any amount of time. This the most basic building block + * A representation of any set of values over any amount of time. This is the most basic building block * of RxJS. * * @class Observable @@ -5393,7 +5574,7 @@ var observable_1 = require('./symbol/observable'); var Observable = (function () { /** * @constructor - * @param {Function} subscribe the function that is called when the Observable is + * @param {Function} subscribe the function that is called when the Observable is * initially subscribed to. This function is given a Subscriber, to which new values * can be `next`ed, or an `error` method can be called to raise an error, or * `complete` can be called to notify of a successful completion. @@ -5418,24 +5599,127 @@ var Observable = (function () { return observable; }; /** - * Registers handlers for handling emitted values, error and completions from the observable, and - * executes the observable's subscriber function, which will take action to set up the underlying data stream - * @method subscribe - * @param {PartialObserver|Function} observerOrNext (optional) either an observer defining all functions to be called, - * or the first of three possible handlers, which is the handler for each value emitted from the observable. - * @param {Function} error (optional) a handler for a terminal event resulting from an error. If no error handler is provided, - * the error will be thrown as unhandled - * @param {Function} complete (optional) a handler for a terminal event resulting from successful completion. + * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. + * + * Use it when you have all these Observables, but still nothing is happening. + * + * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It + * might be for example a function that you passed to a {@link create} static factory, but most of the time it is + * a library implementation, which defines what and when will be emitted by an Observable. This means that calling + * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often + * thought. + * + * Apart from starting the execution of an Observable, this method allows you to listen for values + * that an Observable emits, as well as for when it completes or errors. You can achieve this in two + * following ways. + * + * The first way is creating an object that implements {@link Observer} interface. It should have methods + * defined by that interface, but note that it should be just a regular JavaScript object, which you can create + * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do + * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also + * that your object does not have to implement all methods. If you find yourself creating a method that doesn't + * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will + * be left uncaught. + * + * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods. + * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent + * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer, + * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`, + * since `subscribe` recognizes these functions by where they were placed in function call. When it comes + * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown. + * + * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object. + * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean + * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback + * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable. + * + * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously. + * It is an Observable itself that decides when these functions will be called. For example {@link of} + * by default emits all its values synchronously. Always check documentation for how given Observable + * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}. + * + * @example Subscribe with an Observer + * const sumObserver = { + * sum: 0, + * next(value) { + * console.log('Adding: ' + value); + * this.sum = this.sum + value; + * }, + * error() { // We actually could just remove this method, + * }, // since we do not really care about errors right now. + * complete() { + * console.log('Sum equals: ' + this.sum); + * } + * }; + * + * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes. + * .subscribe(sumObserver); + * + * // Logs: + * // "Adding: 1" + * // "Adding: 2" + * // "Adding: 3" + * // "Sum equals: 6" + * + * + * @example Subscribe with functions + * let sum = 0; + * + * Rx.Observable.of(1, 2, 3) + * .subscribe( + * function(value) { + * console.log('Adding: ' + value); + * sum = sum + value; + * }, + * undefined, + * function() { + * console.log('Sum equals: ' + sum); + * } + * ); + * + * // Logs: + * // "Adding: 1" + * // "Adding: 2" + * // "Adding: 3" + * // "Sum equals: 6" + * + * + * @example Cancel a subscription + * const subscription = Rx.Observable.interval(1000).subscribe( + * num => console.log(num), + * undefined, + * () => console.log('completed!') // Will not be called, even + * ); // when cancelling subscription + * + * + * setTimeout(() => { + * subscription.unsubscribe(); + * console.log('unsubscribed!'); + * }, 2500); + * + * // Logs: + * // 0 after 1s + * // 1 after 2s + * // "unsubscribed!" after 2.5s + * + * + * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called, + * or the first of three possible handlers, which is the handler for each value emitted from the subscribed + * Observable. + * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided, + * the error will be thrown as unhandled. + * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion. * @return {ISubscription} a subscription reference to the registered handlers + * @method subscribe */ Observable.prototype.subscribe = function (observerOrNext, error, complete) { var operator = this.operator; var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete); if (operator) { - operator.call(sink, this); + operator.call(sink, this.source); } else { - sink.add(this._subscribe(sink)); + sink.add(this.source ? this._subscribe(sink) : this._trySubscribe(sink)); } if (sink.syncErrorThrowable) { sink.syncErrorThrowable = false; @@ -5445,6 +5729,16 @@ var Observable = (function () { } return sink; }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + sink.error(err); + } + }; /** * @method forEach * @param {Function} next a handler for each value emitted by the observable @@ -5466,7 +5760,10 @@ var Observable = (function () { throw new Error('no Promise impl found'); } return new PromiseCtor(function (resolve, reject) { - var subscription = _this.subscribe(function (value) { + // Must be declared in a separate statement to avoid a RefernceError when + // accessing subscription below in the closure due to Temporal Dead Zone. + var subscription; + subscription = _this.subscribe(function (value) { if (subscription) { // if there is a subscription, then we can surmise // the next handling is asynchronous. Any errors thrown @@ -5500,9 +5797,57 @@ var Observable = (function () { * @method Symbol.observable * @return {Observable} this instance of the observable */ - Observable.prototype[observable_1.$$observable] = function () { + Observable.prototype[observable_1.observable] = function () { return this; }; + /* tslint:enable:max-line-length */ + /** + * Used to stitch together functional operators into a chain. + * @method pipe + * @return {Observable} the Observable result of all of the operators having + * been called in the order they were passed in. + * + * @example + * + * import { map, filter, scan } from 'rxjs/operators'; + * + * Rx.Observable.interval(1000) + * .pipe( + * filter(x => x % 2 === 0), + * map(x => x + x), + * scan((acc, x) => acc + x) + * ) + * .subscribe(x => console.log(x)) + */ + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i - 0] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return pipe_1.pipeFromArray(operations)(this); + }; + /* tslint:enable:max-line-length */ + Observable.prototype.toPromise = function (PromiseCtor) { + var _this = this; + if (!PromiseCtor) { + if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) { + PromiseCtor = root_1.root.Rx.config.Promise; + } + else if (root_1.root.Promise) { + PromiseCtor = root_1.root.Promise; + } + } + if (!PromiseCtor) { + throw new Error('no Promise impl found'); + } + return new PromiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; // HACK: Since TypeScript inherits static properties too, we have to // fight against TypeScript here so Subject can have a different static create signature /** @@ -5520,7 +5865,7 @@ var Observable = (function () { }()); exports.Observable = Observable; -},{"./symbol/observable":141,"./util/root":153,"./util/toSubscriber":155}],29:[function(require,module,exports){ +},{"./symbol/observable":215,"./util/pipe":235,"./util/root":236,"./util/toSubscriber":238}],30:[function(require,module,exports){ "use strict"; exports.empty = { closed: true, @@ -5529,7 +5874,7 @@ exports.empty = { complete: function () { } }; -},{}],30:[function(require,module,exports){ +},{}],31:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -5560,7 +5905,7 @@ var OuterSubscriber = (function (_super) { }(Subscriber_1.Subscriber)); exports.OuterSubscriber = OuterSubscriber; -},{"./Subscriber":35}],31:[function(require,module,exports){ +},{"./Subscriber":36}],32:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -5569,7 +5914,10 @@ var __extends = (this && this.__extends) || function (d, b) { }; var Subject_1 = require('./Subject'); var queue_1 = require('./scheduler/queue'); -var observeOn_1 = require('./operator/observeOn'); +var Subscription_1 = require('./Subscription'); +var observeOn_1 = require('./operators/observeOn'); +var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError'); +var SubjectSubscription_1 = require('./SubjectSubscription'); /** * @class ReplaySubject */ @@ -5593,6 +5941,20 @@ var ReplaySubject = (function (_super) { ReplaySubject.prototype._subscribe = function (subscriber) { var _events = this._trimBufferThenGetEvents(); var scheduler = this.scheduler; + var subscription; + if (this.closed) { + throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError(); + } + else if (this.hasError) { + subscription = Subscription_1.Subscription.EMPTY; + } + else if (this.isStopped) { + subscription = Subscription_1.Subscription.EMPTY; + } + else { + this.observers.push(subscriber); + subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber); + } if (scheduler) { subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler)); } @@ -5600,7 +5962,13 @@ var ReplaySubject = (function (_super) { for (var i = 0; i < len && !subscriber.closed; i++) { subscriber.next(_events[i].value); } - return _super.prototype._subscribe.call(this, subscriber); + if (this.hasError) { + subscriber.error(this.thrownError); + } + else if (this.isStopped) { + subscriber.complete(); + } + return subscription; }; ReplaySubject.prototype._getNow = function () { return (this.scheduler || queue_1.queue).now(); @@ -5640,7 +6008,7 @@ var ReplayEvent = (function () { return ReplayEvent; }()); -},{"./Subject":33,"./operator/observeOn":118,"./scheduler/queue":139}],32:[function(require,module,exports){ +},{"./Subject":34,"./SubjectSubscription":35,"./Subscription":37,"./operators/observeOn":183,"./scheduler/queue":213,"./util/ObjectUnsubscribedError":220}],33:[function(require,module,exports){ "use strict"; /** * An execution context and a data structure to order tasks and schedule their @@ -5690,7 +6058,7 @@ var Scheduler = (function () { }()); exports.Scheduler = Scheduler; -},{}],33:[function(require,module,exports){ +},{}],34:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -5728,7 +6096,7 @@ var Subject = (function (_super) { this.hasError = false; this.thrownError = null; } - Subject.prototype[rxSubscriber_1.$$rxSubscriber] = function () { + Subject.prototype[rxSubscriber_1.rxSubscriber] = function () { return new SubjectSubscriber(this); }; Subject.prototype.lift = function (operator) { @@ -5782,6 +6150,14 @@ var Subject = (function (_super) { this.closed = true; this.observers = null; }; + Subject.prototype._trySubscribe = function (subscriber) { + if (this.closed) { + throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError(); + } + else { + return _super.prototype._trySubscribe.call(this, subscriber); + } + }; Subject.prototype._subscribe = function (subscriber) { if (this.closed) { throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError(); @@ -5851,7 +6227,7 @@ var AnonymousSubject = (function (_super) { }(Subject)); exports.AnonymousSubject = AnonymousSubject; -},{"./Observable":28,"./SubjectSubscription":34,"./Subscriber":35,"./Subscription":36,"./symbol/rxSubscriber":142,"./util/ObjectUnsubscribedError":145}],34:[function(require,module,exports){ +},{"./Observable":29,"./SubjectSubscription":35,"./Subscriber":36,"./Subscription":37,"./symbol/rxSubscriber":216,"./util/ObjectUnsubscribedError":220}],35:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -5892,7 +6268,7 @@ var SubjectSubscription = (function (_super) { }(Subscription_1.Subscription)); exports.SubjectSubscription = SubjectSubscription; -},{"./Subscription":36}],35:[function(require,module,exports){ +},{"./Subscription":37}],36:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -5955,7 +6331,7 @@ var Subscriber = (function (_super) { break; } } - Subscriber.prototype[rxSubscriber_1.$$rxSubscriber] = function () { return this; }; + Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; }; /** * A static factory for a Subscriber, given a (potentially partial) definition * of an Observer. @@ -6027,6 +6403,17 @@ var Subscriber = (function (_super) { this.destination.complete(); this.unsubscribe(); }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _a = this, _parent = _a._parent, _parents = _a._parents; + this._parent = null; + this._parents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parent = _parent; + this._parents = _parents; + return this; + }; return Subscriber; }(Subscription_1.Subscription)); exports.Subscriber = Subscriber; @@ -6037,23 +6424,25 @@ exports.Subscriber = Subscriber; */ var SafeSubscriber = (function (_super) { __extends(SafeSubscriber, _super); - function SafeSubscriber(_parent, observerOrNext, error, complete) { + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { _super.call(this); - this._parent = _parent; + this._parentSubscriber = _parentSubscriber; var next; var context = this; if (isFunction_1.isFunction(observerOrNext)) { next = observerOrNext; } else if (observerOrNext) { - context = observerOrNext; next = observerOrNext.next; error = observerOrNext.error; complete = observerOrNext.complete; - if (isFunction_1.isFunction(context.unsubscribe)) { - this.add(context.unsubscribe.bind(context)); + if (observerOrNext !== Observer_1.empty) { + context = Object.create(observerOrNext); + if (isFunction_1.isFunction(context.unsubscribe)) { + this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = this.unsubscribe.bind(this); } - context.unsubscribe = this.unsubscribe.bind(this); } this._context = context; this._next = next; @@ -6062,49 +6451,51 @@ var SafeSubscriber = (function (_super) { } SafeSubscriber.prototype.next = function (value) { if (!this.isStopped && this._next) { - var _parent = this._parent; - if (!_parent.syncErrorThrowable) { + var _parentSubscriber = this._parentSubscriber; + if (!_parentSubscriber.syncErrorThrowable) { this.__tryOrUnsub(this._next, value); } - else if (this.__tryOrSetError(_parent, this._next, value)) { + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { this.unsubscribe(); } } }; SafeSubscriber.prototype.error = function (err) { if (!this.isStopped) { - var _parent = this._parent; + var _parentSubscriber = this._parentSubscriber; if (this._error) { - if (!_parent.syncErrorThrowable) { + if (!_parentSubscriber.syncErrorThrowable) { this.__tryOrUnsub(this._error, err); this.unsubscribe(); } else { - this.__tryOrSetError(_parent, this._error, err); + this.__tryOrSetError(_parentSubscriber, this._error, err); this.unsubscribe(); } } - else if (!_parent.syncErrorThrowable) { + else if (!_parentSubscriber.syncErrorThrowable) { this.unsubscribe(); throw err; } else { - _parent.syncErrorValue = err; - _parent.syncErrorThrown = true; + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; this.unsubscribe(); } } }; SafeSubscriber.prototype.complete = function () { + var _this = this; if (!this.isStopped) { - var _parent = this._parent; + var _parentSubscriber = this._parentSubscriber; if (this._complete) { - if (!_parent.syncErrorThrowable) { - this.__tryOrUnsub(this._complete); + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); this.unsubscribe(); } else { - this.__tryOrSetError(_parent, this._complete); + this.__tryOrSetError(_parentSubscriber, wrappedComplete); this.unsubscribe(); } } @@ -6134,15 +6525,15 @@ var SafeSubscriber = (function (_super) { return false; }; SafeSubscriber.prototype._unsubscribe = function () { - var _parent = this._parent; + var _parentSubscriber = this._parentSubscriber; this._context = null; - this._parent = null; - _parent.unsubscribe(); + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); }; return SafeSubscriber; }(Subscriber)); -},{"./Observer":29,"./Subscription":36,"./symbol/rxSubscriber":142,"./util/isFunction":149}],36:[function(require,module,exports){ +},{"./Observer":30,"./Subscription":37,"./symbol/rxSubscriber":216,"./util/isFunction":229}],37:[function(require,module,exports){ "use strict"; var isArray_1 = require('./util/isArray'); var isObject_1 = require('./util/isObject'); @@ -6173,6 +6564,9 @@ var Subscription = (function () { * @type {boolean} */ this.closed = false; + this._parent = null; + this._parents = null; + this._subscriptions = null; if (unsubscribe) { this._unsubscribe = unsubscribe; } @@ -6189,19 +6583,34 @@ var Subscription = (function () { if (this.closed) { return; } + var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; this.closed = true; - var _a = this, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this._parent = null; + this._parents = null; + // null out _subscriptions first so any child subscriptions that attempt + // to remove themselves from this subscription will noop this._subscriptions = null; + var index = -1; + var len = _parents ? _parents.length : 0; + // if this._parent is null, then so is this._parents, and we + // don't have to remove ourselves from any parent subscriptions. + while (_parent) { + _parent.remove(this); + // if this._parents is null or index >= len, + // then _parent is set to null, and the loop exits + _parent = ++index < len && _parents[index] || null; + } if (isFunction_1.isFunction(_unsubscribe)) { var trial = tryCatch_1.tryCatch(_unsubscribe).call(this); if (trial === errorObject_1.errorObject) { hasErrors = true; - (errors = errors || []).push(errorObject_1.errorObject.e); + errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ? + flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]); } } if (isArray_1.isArray(_subscriptions)) { - var index = -1; - var len = _subscriptions.length; + index = -1; + len = _subscriptions.length; while (++index < len) { var sub = _subscriptions[index]; if (isObject_1.isObject(sub)) { @@ -6211,7 +6620,7 @@ var Subscription = (function () { errors = errors || []; var err = errorObject_1.errorObject.e; if (err instanceof UnsubscriptionError_1.UnsubscriptionError) { - errors = errors.concat(err.errors); + errors = errors.concat(flattenUnsubscriptionErrors(err.errors)); } else { errors.push(err); @@ -6249,25 +6658,31 @@ var Subscription = (function () { if (teardown === this) { return this; } - var sub = teardown; + var subscription = teardown; switch (typeof teardown) { case 'function': - sub = new Subscription(teardown); + subscription = new Subscription(teardown); case 'object': - if (sub.closed || typeof sub.unsubscribe !== 'function') { - break; + if (subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; } else if (this.closed) { - sub.unsubscribe(); + subscription.unsubscribe(); + return subscription; } - else { - (this._subscriptions || (this._subscriptions = [])).push(sub); + else if (typeof subscription._addParent !== 'function' /* quack quack */) { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; } break; default: throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } - return sub; + var subscriptions = this._subscriptions || (this._subscriptions = []); + subscriptions.push(subscription); + subscription._addParent(this); + return subscription; }; /** * Removes a Subscription from the internal list of subscriptions that will @@ -6276,10 +6691,6 @@ var Subscription = (function () { * @return {void} */ Subscription.prototype.remove = function (subscription) { - // HACK: This might be redundant because of the logic in `add()` - if (subscription == null || (subscription === this) || (subscription === Subscription.EMPTY)) { - return; - } var subscriptions = this._subscriptions; if (subscriptions) { var subscriptionIndex = subscriptions.indexOf(subscription); @@ -6288,6 +6699,23 @@ var Subscription = (function () { } } }; + Subscription.prototype._addParent = function (parent) { + var _a = this, _parent = _a._parent, _parents = _a._parents; + if (!_parent || _parent === parent) { + // If we don't have a parent, or the new parent is the same as the + // current parent, then set this._parent to the new parent. + this._parent = parent; + } + else if (!_parents) { + // If there's already one parent, but not multiple, allocate an Array to + // store the rest of the parent Subscriptions. + this._parents = [parent]; + } + else if (_parents.indexOf(parent) === -1) { + // Only add the new parent to the _parents list if it's not already there. + _parents.push(parent); + } + }; Subscription.EMPTY = (function (empty) { empty.closed = true; return empty; @@ -6295,258 +6723,339 @@ var Subscription = (function () { return Subscription; }()); exports.Subscription = Subscription; +function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []); +} -},{"./util/UnsubscriptionError":146,"./util/errorObject":147,"./util/isArray":148,"./util/isFunction":149,"./util/isObject":150,"./util/tryCatch":156}],37:[function(require,module,exports){ +},{"./util/UnsubscriptionError":223,"./util/errorObject":224,"./util/isArray":226,"./util/isFunction":229,"./util/isObject":231,"./util/tryCatch":239}],38:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var combineLatest_1 = require('../../observable/combineLatest'); Observable_1.Observable.combineLatest = combineLatest_1.combineLatest; -},{"../../Observable":28,"../../observable/combineLatest":90}],38:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/combineLatest":104}],39:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var concat_1 = require('../../observable/concat'); +Observable_1.Observable.concat = concat_1.concat; + +},{"../../Observable":29,"../../observable/concat":105}],40:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var defer_1 = require('../../observable/defer'); Observable_1.Observable.defer = defer_1.defer; -},{"../../Observable":28,"../../observable/defer":91}],39:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/defer":106}],41:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var empty_1 = require('../../observable/empty'); Observable_1.Observable.empty = empty_1.empty; -},{"../../Observable":28,"../../observable/empty":92}],40:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/empty":107}],42:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var from_1 = require('../../observable/from'); Observable_1.Observable.from = from_1.from; -},{"../../Observable":28,"../../observable/from":93}],41:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/from":108}],43:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var fromEvent_1 = require('../../observable/fromEvent'); Observable_1.Observable.fromEvent = fromEvent_1.fromEvent; -},{"../../Observable":28,"../../observable/fromEvent":94}],42:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/fromEvent":109}],44:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var fromPromise_1 = require('../../observable/fromPromise'); Observable_1.Observable.fromPromise = fromPromise_1.fromPromise; -},{"../../Observable":28,"../../observable/fromPromise":95}],43:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/fromPromise":110}],45:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var merge_1 = require('../../observable/merge'); Observable_1.Observable.merge = merge_1.merge; -},{"../../Observable":28,"../../observable/merge":96}],44:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/merge":111}],46:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var of_1 = require('../../observable/of'); Observable_1.Observable.of = of_1.of; -},{"../../Observable":28,"../../observable/of":97}],45:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/of":112}],47:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var throw_1 = require('../../observable/throw'); Observable_1.Observable.throw = throw_1._throw; -},{"../../Observable":28,"../../observable/throw":98}],46:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/throw":113}],48:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var timer_1 = require('../../observable/timer'); +Observable_1.Observable.timer = timer_1.timer; + +},{"../../Observable":29,"../../observable/timer":114}],49:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var zip_1 = require('../../observable/zip'); Observable_1.Observable.zip = zip_1.zip; -},{"../../Observable":28,"../../observable/zip":99}],47:[function(require,module,exports){ +},{"../../Observable":29,"../../observable/zip":115}],50:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var auditTime_1 = require('../../operator/auditTime'); +Observable_1.Observable.prototype.auditTime = auditTime_1.auditTime; + +},{"../../Observable":29,"../../operator/auditTime":116}],51:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var buffer_1 = require('../../operator/buffer'); Observable_1.Observable.prototype.buffer = buffer_1.buffer; -},{"../../Observable":28,"../../operator/buffer":100}],48:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/buffer":117}],52:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var bufferCount_1 = require('../../operator/bufferCount'); +Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount; + +},{"../../Observable":29,"../../operator/bufferCount":118}],53:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var bufferWhen_1 = require('../../operator/bufferWhen'); +Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen; + +},{"../../Observable":29,"../../operator/bufferWhen":119}],54:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var catch_1 = require('../../operator/catch'); Observable_1.Observable.prototype.catch = catch_1._catch; Observable_1.Observable.prototype._catch = catch_1._catch; -},{"../../Observable":28,"../../operator/catch":101}],49:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/catch":120}],55:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var combineLatest_1 = require('../../operator/combineLatest'); Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest; -},{"../../Observable":28,"../../operator/combineLatest":102}],50:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/combineLatest":121}],56:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var concat_1 = require('../../operator/concat'); Observable_1.Observable.prototype.concat = concat_1.concat; -},{"../../Observable":28,"../../operator/concat":103}],51:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/concat":122}],57:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var count_1 = require('../../operator/count'); +Observable_1.Observable.prototype.count = count_1.count; + +},{"../../Observable":29,"../../operator/count":123}],58:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var debounceTime_1 = require('../../operator/debounceTime'); Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime; -},{"../../Observable":28,"../../operator/debounceTime":104}],52:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/debounceTime":124}],59:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var delay_1 = require('../../operator/delay'); +Observable_1.Observable.prototype.delay = delay_1.delay; + +},{"../../Observable":29,"../../operator/delay":125}],60:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var distinct_1 = require('../../operator/distinct'); Observable_1.Observable.prototype.distinct = distinct_1.distinct; -},{"../../Observable":28,"../../operator/distinct":105}],53:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/distinct":126}],61:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged'); Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged; -},{"../../Observable":28,"../../operator/distinctUntilChanged":106}],54:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/distinctUntilChanged":127}],62:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var do_1 = require('../../operator/do'); Observable_1.Observable.prototype.do = do_1._do; Observable_1.Observable.prototype._do = do_1._do; -},{"../../Observable":28,"../../operator/do":107}],55:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/do":128}],63:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var expand_1 = require('../../operator/expand'); Observable_1.Observable.prototype.expand = expand_1.expand; -},{"../../Observable":28,"../../operator/expand":108}],56:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/expand":129}],64:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var filter_1 = require('../../operator/filter'); Observable_1.Observable.prototype.filter = filter_1.filter; -},{"../../Observable":28,"../../operator/filter":109}],57:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/filter":130}],65:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var finally_1 = require('../../operator/finally'); Observable_1.Observable.prototype.finally = finally_1._finally; Observable_1.Observable.prototype._finally = finally_1._finally; -},{"../../Observable":28,"../../operator/finally":110}],58:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/finally":131}],66:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var first_1 = require('../../operator/first'); Observable_1.Observable.prototype.first = first_1.first; -},{"../../Observable":28,"../../operator/first":111}],59:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/first":132}],67:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var last_1 = require('../../operator/last'); Observable_1.Observable.prototype.last = last_1.last; -},{"../../Observable":28,"../../operator/last":112}],60:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/last":133}],68:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var map_1 = require('../../operator/map'); Observable_1.Observable.prototype.map = map_1.map; -},{"../../Observable":28,"../../operator/map":113}],61:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/map":134}],69:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var merge_1 = require('../../operator/merge'); Observable_1.Observable.prototype.merge = merge_1.merge; -},{"../../Observable":28,"../../operator/merge":114}],62:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/merge":135}],70:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var mergeAll_1 = require('../../operator/mergeAll'); Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll; -},{"../../Observable":28,"../../operator/mergeAll":115}],63:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/mergeAll":136}],71:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var mergeMap_1 = require('../../operator/mergeMap'); Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap; Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap; -},{"../../Observable":28,"../../operator/mergeMap":116}],64:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/mergeMap":137}],72:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var pairwise_1 = require('../../operator/pairwise'); Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise; -},{"../../Observable":28,"../../operator/pairwise":119}],65:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/pairwise":138}],73:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var pluck_1 = require('../../operator/pluck'); Observable_1.Observable.prototype.pluck = pluck_1.pluck; -},{"../../Observable":28,"../../operator/pluck":120}],66:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/pluck":139}],74:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var publish_1 = require('../../operator/publish'); Observable_1.Observable.prototype.publish = publish_1.publish; -},{"../../Observable":28,"../../operator/publish":121}],67:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/publish":140}],75:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var publishReplay_1 = require('../../operator/publishReplay'); Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay; -},{"../../Observable":28,"../../operator/publishReplay":122}],68:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/publishReplay":141}],76:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var reduce_1 = require('../../operator/reduce'); +Observable_1.Observable.prototype.reduce = reduce_1.reduce; + +},{"../../Observable":29,"../../operator/reduce":142}],77:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var retry_1 = require('../../operator/retry'); +Observable_1.Observable.prototype.retry = retry_1.retry; + +},{"../../Observable":29,"../../operator/retry":143}],78:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var sample_1 = require('../../operator/sample'); +Observable_1.Observable.prototype.sample = sample_1.sample; + +},{"../../Observable":29,"../../operator/sample":144}],79:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var scan_1 = require('../../operator/scan'); Observable_1.Observable.prototype.scan = scan_1.scan; -},{"../../Observable":28,"../../operator/scan":123}],69:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/scan":145}],80:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var share_1 = require('../../operator/share'); Observable_1.Observable.prototype.share = share_1.share; -},{"../../Observable":28,"../../operator/share":124}],70:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/share":146}],81:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var skip_1 = require('../../operator/skip'); Observable_1.Observable.prototype.skip = skip_1.skip; -},{"../../Observable":28,"../../operator/skip":125}],71:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/skip":147}],82:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var skipUntil_1 = require('../../operator/skipUntil'); Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil; -},{"../../Observable":28,"../../operator/skipUntil":126}],72:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/skipUntil":148}],83:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var skipWhile_1 = require('../../operator/skipWhile'); +Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile; + +},{"../../Observable":29,"../../operator/skipWhile":149}],84:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var startWith_1 = require('../../operator/startWith'); Observable_1.Observable.prototype.startWith = startWith_1.startWith; -},{"../../Observable":28,"../../operator/startWith":127}],73:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/startWith":150}],85:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var switchMap_1 = require('../../operator/switchMap'); Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap; -},{"../../Observable":28,"../../operator/switchMap":128}],74:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/switchMap":151}],86:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var take_1 = require('../../operator/take'); Observable_1.Observable.prototype.take = take_1.take; -},{"../../Observable":28,"../../operator/take":129}],75:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/take":152}],87:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var takeUntil_1 = require('../../operator/takeUntil'); Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil; -},{"../../Observable":28,"../../operator/takeUntil":130}],76:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/takeUntil":153}],88:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var takeWhile_1 = require('../../operator/takeWhile'); +Observable_1.Observable.prototype.takeWhile = takeWhile_1.takeWhile; + +},{"../../Observable":29,"../../operator/takeWhile":154}],89:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../../Observable'); +var timeout_1 = require('../../operator/timeout'); +Observable_1.Observable.prototype.timeout = timeout_1.timeout; + +},{"../../Observable":29,"../../operator/timeout":155}],90:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var withLatestFrom_1 = require('../../operator/withLatestFrom'); Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom; -},{"../../Observable":28,"../../operator/withLatestFrom":131}],77:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/withLatestFrom":156}],91:[function(require,module,exports){ "use strict"; var Observable_1 = require('../../Observable'); var zip_1 = require('../../operator/zip'); Observable_1.Observable.prototype.zip = zip_1.zipProto; -},{"../../Observable":28,"../../operator/zip":132}],78:[function(require,module,exports){ +},{"../../Observable":29,"../../operator/zip":157}],92:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -6617,7 +7126,7 @@ var ArrayLikeObservable = (function (_super) { }(Observable_1.Observable)); exports.ArrayLikeObservable = ArrayLikeObservable; -},{"../Observable":28,"./EmptyObservable":82,"./ScalarObservable":89}],79:[function(require,module,exports){ +},{"../Observable":29,"./EmptyObservable":96,"./ScalarObservable":102}],93:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -6659,8 +7168,8 @@ var ArrayObservable = (function (_super) { * This static operator is useful for creating a simple Observable that only * emits the arguments given, and the complete notification thereafter. It can * be used for composing with other Observables, such as with {@link concat}. - * By default, it uses a `null` Scheduler, which means the `next` - * notifications are sent synchronously, although with a different Scheduler + * By default, it uses a `null` IScheduler, which means the `next` + * notifications are sent synchronously, although with a different IScheduler * it is possible to determine when those notifications will be delivered. * * @example Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second. @@ -6676,7 +7185,7 @@ var ArrayObservable = (function (_super) { * @see {@link throw} * * @param {...T} values Arguments that represent `next` values to be emitted. - * @param {Scheduler} [scheduler] A {@link Scheduler} to use for scheduling + * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling * the emissions of the `next` notifications. * @return {Observable} An Observable that emits each given input value. * @static true @@ -6740,7 +7249,7 @@ var ArrayObservable = (function (_super) { }(Observable_1.Observable)); exports.ArrayObservable = ArrayObservable; -},{"../Observable":28,"../util/isScheduler":152,"./EmptyObservable":82,"./ScalarObservable":89}],80:[function(require,module,exports){ +},{"../Observable":29,"../util/isScheduler":233,"./EmptyObservable":96,"./ScalarObservable":102}],94:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -6751,6 +7260,7 @@ var Subject_1 = require('../Subject'); var Observable_1 = require('../Observable'); var Subscriber_1 = require('../Subscriber'); var Subscription_1 = require('../Subscription'); +var refCount_1 = require('../operators/refCount'); /** * @class ConnectableObservable */ @@ -6761,6 +7271,7 @@ var ConnectableObservable = (function (_super) { this.source = source; this.subjectFactory = subjectFactory; this._refCount = 0; + this._isComplete = false; } ConnectableObservable.prototype._subscribe = function (subscriber) { return this.getSubject().subscribe(subscriber); @@ -6775,6 +7286,7 @@ var ConnectableObservable = (function (_super) { ConnectableObservable.prototype.connect = function () { var connection = this._connection; if (!connection) { + this._isComplete = false; connection = this._connection = new Subscription_1.Subscription(); connection.add(this.source .subscribe(new ConnectableSubscriber(this.getSubject(), this))); @@ -6789,11 +7301,23 @@ var ConnectableObservable = (function (_super) { return connection; }; ConnectableObservable.prototype.refCount = function () { - return this.lift(new RefCountOperator(this)); + return refCount_1.refCount()(this); }; return ConnectableObservable; }(Observable_1.Observable)); exports.ConnectableObservable = ConnectableObservable; +var connectableProto = ConnectableObservable.prototype; +exports.connectableObservableDescriptor = { + operator: { value: null }, + _refCount: { value: 0, writable: true }, + _subject: { value: null, writable: true }, + _connection: { value: null, writable: true }, + _subscribe: { value: connectableProto._subscribe }, + _isComplete: { value: connectableProto._isComplete, writable: true }, + getSubject: { value: connectableProto.getSubject }, + connect: { value: connectableProto.connect }, + refCount: { value: connectableProto.refCount } +}; var ConnectableSubscriber = (function (_super) { __extends(ConnectableSubscriber, _super); function ConnectableSubscriber(destination, connectable) { @@ -6805,6 +7329,7 @@ var ConnectableSubscriber = (function (_super) { _super.prototype._error.call(this, err); }; ConnectableSubscriber.prototype._complete = function () { + this.connectable._isComplete = true; this._unsubscribe(); _super.prototype._complete.call(this); }; @@ -6831,7 +7356,7 @@ var RefCountOperator = (function () { var connectable = this.connectable; connectable._refCount++; var refCounter = new RefCountSubscriber(subscriber, connectable); - var subscription = source._subscribe(refCounter); + var subscription = source.subscribe(refCounter); if (!refCounter.closed) { refCounter.connection = connectable.connect(); } @@ -6866,7 +7391,7 @@ var RefCountSubscriber = (function (_super) { // Compare the local RefCountSubscriber's connection Subscription to the // connection Subscription on the shared ConnectableObservable. In cases // where the ConnectableObservable source synchronously emits values, and - // the RefCountSubscriber's dowstream Observers synchronously unsubscribe, + // the RefCountSubscriber's downstream Observers synchronously unsubscribe, // execution continues to here before the RefCountOperator has a chance to // supply the RefCountSubscriber with the shared connection Subscription. // For example: @@ -6895,7 +7420,7 @@ var RefCountSubscriber = (function (_super) { return RefCountSubscriber; }(Subscriber_1.Subscriber)); -},{"../Observable":28,"../Subject":33,"../Subscriber":35,"../Subscription":36}],81:[function(require,module,exports){ +},{"../Observable":29,"../Subject":34,"../Subscriber":36,"../Subscription":37,"../operators/refCount":189}],95:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -6944,9 +7469,15 @@ var DeferObservable = (function (_super) { * }); * clicksOrInterval.subscribe(x => console.log(x)); * + * // Results in the following behavior: + * // If the result of Math.random() is greater than 0.5 it will listen + * // for clicks anywhere on the "document"; when document is clicked it + * // will log a MouseEvent object to the console. If the result is less + * // than 0.5 it will emit ascending numbers, one every second(1000ms). + * * @see {@link create} * - * @param {function(): Observable|Promise} observableFactory The Observable + * @param {function(): SubscribableOrPromise} observableFactory The Observable * factory function to invoke for each Observer that subscribes to the output * Observable. May also return a Promise, which will be converted on the fly * to an Observable. @@ -6989,7 +7520,7 @@ var DeferSubscriber = (function (_super) { return DeferSubscriber; }(OuterSubscriber_1.OuterSubscriber)); -},{"../Observable":28,"../OuterSubscriber":30,"../util/subscribeToResult":154}],82:[function(require,module,exports){ +},{"../Observable":29,"../OuterSubscriber":31,"../util/subscribeToResult":237}],96:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -7032,12 +7563,18 @@ var EmptyObservable = (function (_super) { * ); * result.subscribe(x => console.log(x)); * + * // Results in the following to the console: + * // x is equal to the count on the interval eg(0,1,2,3,...) + * // x will occur every 1000ms + * // if x % 2 is equal to 1 print abc + * // if x % 2 is not equal to 1 nothing will be output + * * @see {@link create} * @see {@link never} * @see {@link of} * @see {@link throw} * - * @param {Scheduler} [scheduler] A {@link Scheduler} to use for scheduling + * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling * the emission of the complete notification. * @return {Observable} An "empty" Observable: emits only the complete * notification. @@ -7065,7 +7602,7 @@ var EmptyObservable = (function (_super) { }(Observable_1.Observable)); exports.EmptyObservable = EmptyObservable; -},{"../Observable":28}],83:[function(require,module,exports){ +},{"../Observable":29}],97:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -7102,7 +7639,7 @@ var ErrorObservable = (function (_super) { * var result = Rx.Observable.throw(new Error('oops!')).startWith(7); * result.subscribe(x => console.log(x), e => console.error(e)); * - * @example Map and flattens numbers to the sequence 'a', 'b', 'c', but throw an error for 13 + * @example Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13 * var interval = Rx.Observable.interval(1000); * var result = interval.mergeMap(x => * x === 13 ? @@ -7117,7 +7654,7 @@ var ErrorObservable = (function (_super) { * @see {@link of} * * @param {any} error The particular Error to pass to the error notification. - * @param {Scheduler} [scheduler] A {@link Scheduler} to use for scheduling + * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling * the emission of the error notification. * @return {Observable} An error Observable: emits only the error notification * using the given error argument. @@ -7135,6 +7672,7 @@ var ErrorObservable = (function (_super) { ErrorObservable.prototype._subscribe = function (subscriber) { var error = this.error; var scheduler = this.scheduler; + subscriber.syncErrorThrowable = true; if (scheduler) { return scheduler.schedule(ErrorObservable.dispatch, 0, { error: error, subscriber: subscriber @@ -7148,7 +7686,7 @@ var ErrorObservable = (function (_super) { }(Observable_1.Observable)); exports.ErrorObservable = ErrorObservable; -},{"../Observable":28}],84:[function(require,module,exports){ +},{"../Observable":29}],98:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -7160,17 +7698,18 @@ var tryCatch_1 = require('../util/tryCatch'); var isFunction_1 = require('../util/isFunction'); var errorObject_1 = require('../util/errorObject'); var Subscription_1 = require('../Subscription'); -function isNodeStyleEventEmmitter(sourceObj) { +var toString = Object.prototype.toString; +function isNodeStyleEventEmitter(sourceObj) { return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; } function isJQueryStyleEventEmitter(sourceObj) { return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function'; } function isNodeList(sourceObj) { - return !!sourceObj && sourceObj.toString() === '[object NodeList]'; + return !!sourceObj && toString.call(sourceObj) === '[object NodeList]'; } function isHTMLCollection(sourceObj) { - return !!sourceObj && sourceObj.toString() === '[object HTMLCollection]'; + return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]'; } function isEventTarget(sourceObj) { return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function'; @@ -7194,30 +7733,110 @@ var FromEventObservable = (function (_super) { * Creates an Observable that emits events of a specific type coming from the * given event target. * - * Creates an Observable from DOM events, or Node + * Creates an Observable from DOM events, or Node.js * EventEmitter events or others. * * * - * Creates an Observable by attaching an event listener to an "event target", - * which may be an object with `addEventListener` and `removeEventListener`, - * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the - * DOM, or an HTMLCollection from the DOM. The event handler is attached when - * the output Observable is subscribed, and removed when the Subscription is - * unsubscribed. + * `fromEvent` accepts as a first argument event target, which is an object with methods + * for registering event handler functions. As a second argument it takes string that indicates + * type of event we want to listen for. `fromEvent` supports selected types of event targets, + * which are described in detail below. If your event target does not match any of the ones listed, + * you should use {@link fromEventPattern}, which can be used on arbitrary APIs. + * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event + * handler functions have different names, but they all accept a string describing event type + * and function itself, which will be called whenever said event happens. + * + * Every time resulting Observable is subscribed, event handler function will be registered + * to event target on given event type. When that event fires, value + * passed as a first argument to registered function will be emitted by output Observable. + * When Observable is unsubscribed, function will be unregistered from event target. + * + * Note that if event target calls registered function with more than one argument, second + * and following arguments will not appear in resulting stream. In order to get access to them, + * you can pass to `fromEvent` optional project function, which will be called with all arguments + * passed to event handler. Output Observable will then emit value returned by project function, + * instead of the usual value. + * + * Remember that event targets listed below are checked via duck typing. It means that + * no matter what kind of object you have and no matter what environment you work in, + * you can safely use `fromEvent` on that object if it exposes described methods (provided + * of course they behave as was described above). So for example if Node.js library exposes + * event target which has the same method names as DOM EventTarget, `fromEvent` is still + * a good choice. + * + * If the API you use is more callback then event handler oriented (subscribed + * callback function fires only once and thus there is no need to manually + * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback} + * instead. + * + * `fromEvent` supports following types of event targets: + * + * **DOM EventTarget** + * + * This is an object with `addEventListener` and `removeEventListener` methods. + * + * In the browser, `addEventListener` accepts - apart from event type string and event + * handler function arguments - optional third parameter, which is either an object or boolean, + * both used for additional configuration how and when passed function will be called. When + * `fromEvent` is used with event target of that type, you can provide this values + * as third parameter as well. + * + * **Node.js EventEmitter** + * + * An object with `addListener` and `removeListener` methods. + * + * **JQuery-style event target** + * + * An object with `on` and `off` methods + * + * **DOM NodeList** + * + * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`. + * + * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes + * it contains and install event handler function in every of them. When returned Observable + * is unsubscribed, function will be removed from all Nodes. + * + * **DOM HtmlCollection** + * + * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is + * installed and removed in each of elements. + * * * @example Emits clicks happening on the DOM document * var clicks = Rx.Observable.fromEvent(document, 'click'); * clicks.subscribe(x => console.log(x)); * - * @see {@link from} + * // Results in: + * // MouseEvent object logged to console every time a click + * // occurs on the document. + * + * + * @example Use addEventListener with capture option + * var clicksInDocument = Rx.Observable.fromEvent(document, 'click', true); // note optional configuration parameter + * // which will be passed to addEventListener + * var clicksInDiv = Rx.Observable.fromEvent(someDivInDocument, 'click'); + * + * clicksInDocument.subscribe(() => console.log('document')); + * clicksInDiv.subscribe(() => console.log('div')); + * + * // By default events bubble UP in DOM tree, so normally + * // when we would click on div in document + * // "div" would be logged first and then "document". + * // Since we specified optional `capture` option, document + * // will catch event when it goes DOWN DOM tree, so console + * // will log "document" and then "div". + * + * @see {@link bindCallback} + * @see {@link bindNodeCallback} * @see {@link fromEventPattern} * - * @param {EventTargetLike} target The DOMElement, event target, Node.js - * EventEmitter, NodeList or HTMLCollection to attach the event handler to. + * @param {EventTargetLike} target The DOM EventTarget, Node.js + * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to. * @param {string} eventName The event name of interest, being emitted by the * `target`. - * @parm {EventListenerOptions} [options] Options to pass through to addEventListener + * @param {EventListenerOptions} [options] Options to pass through to addEventListener * @param {SelectorMethodSignature} [selector] An optional function to * post-process results. It takes the arguments from the event handler and * should return a single value. @@ -7250,11 +7869,14 @@ var FromEventObservable = (function (_super) { sourceObj.on(eventName, handler); unsubscribe = function () { return source_2.off(eventName, handler); }; } - else if (isNodeStyleEventEmmitter(sourceObj)) { + else if (isNodeStyleEventEmitter(sourceObj)) { var source_3 = sourceObj; sourceObj.addListener(eventName, handler); unsubscribe = function () { return source_3.removeListener(eventName, handler); }; } + else { + throw new TypeError('Invalid event target'); + } subscriber.add(new Subscription_1.Subscription(unsubscribe)); }; FromEventObservable.prototype._subscribe = function (subscriber) { @@ -7281,7 +7903,7 @@ var FromEventObservable = (function (_super) { }(Observable_1.Observable)); exports.FromEventObservable = FromEventObservable; -},{"../Observable":28,"../Subscription":36,"../util/errorObject":147,"../util/isFunction":149,"../util/tryCatch":156}],85:[function(require,module,exports){ +},{"../Observable":29,"../Subscription":37,"../util/errorObject":224,"../util/isFunction":229,"../util/tryCatch":239}],99:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -7289,6 +7911,7 @@ var __extends = (this && this.__extends) || function (d, b) { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var isArray_1 = require('../util/isArray'); +var isArrayLike_1 = require('../util/isArrayLike'); var isPromise_1 = require('../util/isPromise'); var PromiseObservable_1 = require('./PromiseObservable'); var IteratorObservable_1 = require('./IteratorObservable'); @@ -7296,9 +7919,8 @@ var ArrayObservable_1 = require('./ArrayObservable'); var ArrayLikeObservable_1 = require('./ArrayLikeObservable'); var iterator_1 = require('../symbol/iterator'); var Observable_1 = require('../Observable'); -var observeOn_1 = require('../operator/observeOn'); +var observeOn_1 = require('../operators/observeOn'); var observable_1 = require('../symbol/observable'); -var isArrayLike = (function (x) { return x && typeof x.length === 'number'; }); /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} @@ -7332,6 +7954,9 @@ var FromObservable = (function (_super) { * var result = Rx.Observable.from(array); * result.subscribe(x => console.log(x)); * + * // Results in the following: + * // 10 20 30 + * * @example Convert an infinite iterable (from a generator) to an Observable * function* generateDoubles(seed) { * var i = seed; @@ -7345,6 +7970,9 @@ var FromObservable = (function (_super) { * var result = Rx.Observable.from(iterator).take(10); * result.subscribe(x => console.log(x)); * + * // Results in the following: + * // 3 6 12 24 48 96 192 384 768 1536 + * * @see {@link create} * @see {@link fromEvent} * @see {@link fromEventPattern} @@ -7363,7 +7991,7 @@ var FromObservable = (function (_super) { */ FromObservable.create = function (ish, scheduler) { if (ish != null) { - if (typeof ish[observable_1.$$observable] === 'function') { + if (typeof ish[observable_1.observable] === 'function') { if (ish instanceof Observable_1.Observable && !scheduler) { return ish; } @@ -7375,10 +8003,10 @@ var FromObservable = (function (_super) { else if (isPromise_1.isPromise(ish)) { return new PromiseObservable_1.PromiseObservable(ish, scheduler); } - else if (typeof ish[iterator_1.$$iterator] === 'function' || typeof ish === 'string') { + else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') { return new IteratorObservable_1.IteratorObservable(ish, scheduler); } - else if (isArrayLike(ish)) { + else if (isArrayLike_1.isArrayLike(ish)) { return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler); } } @@ -7388,17 +8016,17 @@ var FromObservable = (function (_super) { var ish = this.ish; var scheduler = this.scheduler; if (scheduler == null) { - return ish[observable_1.$$observable]().subscribe(subscriber); + return ish[observable_1.observable]().subscribe(subscriber); } else { - return ish[observable_1.$$observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0)); + return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0)); } }; return FromObservable; }(Observable_1.Observable)); exports.FromObservable = FromObservable; -},{"../Observable":28,"../operator/observeOn":118,"../symbol/iterator":140,"../symbol/observable":141,"../util/isArray":148,"../util/isPromise":151,"./ArrayLikeObservable":78,"./ArrayObservable":79,"./IteratorObservable":86,"./PromiseObservable":88}],86:[function(require,module,exports){ +},{"../Observable":29,"../operators/observeOn":183,"../symbol/iterator":214,"../symbol/observable":215,"../util/isArray":226,"../util/isArrayLike":227,"../util/isPromise":232,"./ArrayLikeObservable":92,"./ArrayObservable":93,"./IteratorObservable":100,"./PromiseObservable":101}],100:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -7440,6 +8068,9 @@ var IteratorObservable = (function (_super) { subscriber.next(result.value); state.index = index + 1; if (subscriber.closed) { + if (typeof iterator.return === 'function') { + iterator.return(); + } return; } this.schedule(state); @@ -7463,6 +8094,9 @@ var IteratorObservable = (function (_super) { subscriber.next(result.value); } if (subscriber.closed) { + if (typeof iterator.return === 'function') { + iterator.return(); + } break; } } while (true); @@ -7479,7 +8113,7 @@ var StringIterator = (function () { this.idx = idx; this.len = len; } - StringIterator.prototype[iterator_1.$$iterator] = function () { return (this); }; + StringIterator.prototype[iterator_1.iterator] = function () { return (this); }; StringIterator.prototype.next = function () { return this.idx < this.len ? { done: false, @@ -7499,7 +8133,7 @@ var ArrayIterator = (function () { this.idx = idx; this.len = len; } - ArrayIterator.prototype[iterator_1.$$iterator] = function () { return this; }; + ArrayIterator.prototype[iterator_1.iterator] = function () { return this; }; ArrayIterator.prototype.next = function () { return this.idx < this.len ? { done: false, @@ -7512,7 +8146,7 @@ var ArrayIterator = (function () { return ArrayIterator; }()); function getIterator(obj) { - var i = obj[iterator_1.$$iterator]; + var i = obj[iterator_1.iterator]; if (!i && typeof obj === 'string') { return new StringIterator(obj); } @@ -7522,7 +8156,7 @@ function getIterator(obj) { if (!i) { throw new TypeError('object is not iterable'); } - return obj[iterator_1.$$iterator](); + return obj[iterator_1.iterator](); } var maxSafeInteger = Math.pow(2, 53) - 1; function toLength(o) { @@ -7556,35 +8190,7 @@ function sign(value) { return valueAsNumber < 0 ? -1 : 1; } -},{"../Observable":28,"../symbol/iterator":140,"../util/root":153}],87:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Observable_1 = require('../Observable'); -var ConnectableObservable_1 = require('../observable/ConnectableObservable'); -var MulticastObservable = (function (_super) { - __extends(MulticastObservable, _super); - function MulticastObservable(source, subjectFactory, selector) { - _super.call(this); - this.source = source; - this.subjectFactory = subjectFactory; - this.selector = selector; - } - MulticastObservable.prototype._subscribe = function (subscriber) { - var _a = this, selector = _a.selector, source = _a.source; - var connectable = new ConnectableObservable_1.ConnectableObservable(source, this.subjectFactory); - var subscription = selector(connectable).subscribe(subscriber); - subscription.add(connectable.connect()); - return subscription; - }; - return MulticastObservable; -}(Observable_1.Observable)); -exports.MulticastObservable = MulticastObservable; - -},{"../Observable":28,"../observable/ConnectableObservable":80}],88:[function(require,module,exports){ +},{"../Observable":29,"../symbol/iterator":214,"../util/root":236}],101:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -7623,8 +8229,8 @@ var PromiseObservable = (function (_super) { * @see {@link bindCallback} * @see {@link from} * - * @param {Promise} promise The promise to be converted. - * @param {Scheduler} [scheduler] An optional Scheduler to use for scheduling + * @param {PromiseLike} promise The promise to be converted. + * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling * the delivery of the resolved value (or the rejection). * @return {Observable} An Observable which wraps the Promise. * @static true @@ -7706,7 +8312,7 @@ function dispatchError(arg) { } } -},{"../Observable":28,"../util/root":153}],89:[function(require,module,exports){ +},{"../Observable":29,"../util/root":236}],102:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -7765,12 +8371,120 @@ var ScalarObservable = (function (_super) { }(Observable_1.Observable)); exports.ScalarObservable = ScalarObservable; -},{"../Observable":28}],90:[function(require,module,exports){ +},{"../Observable":29}],103:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var isNumeric_1 = require('../util/isNumeric'); +var Observable_1 = require('../Observable'); +var async_1 = require('../scheduler/async'); +var isScheduler_1 = require('../util/isScheduler'); +var isDate_1 = require('../util/isDate'); +/** + * We need this JSDoc comment for affecting ESDoc. + * @extends {Ignored} + * @hide true + */ +var TimerObservable = (function (_super) { + __extends(TimerObservable, _super); + function TimerObservable(dueTime, period, scheduler) { + if (dueTime === void 0) { dueTime = 0; } + _super.call(this); + this.period = -1; + this.dueTime = 0; + if (isNumeric_1.isNumeric(period)) { + this.period = Number(period) < 1 && 1 || Number(period); + } + else if (isScheduler_1.isScheduler(period)) { + scheduler = period; + } + if (!isScheduler_1.isScheduler(scheduler)) { + scheduler = async_1.async; + } + this.scheduler = scheduler; + this.dueTime = isDate_1.isDate(dueTime) ? + (+dueTime - this.scheduler.now()) : + dueTime; + } + /** + * Creates an Observable that starts emitting after an `initialDelay` and + * emits ever increasing numbers after each `period` of time thereafter. + * + * Its like {@link interval}, but you can specify when + * should the emissions start. + * + * + * + * `timer` returns an Observable that emits an infinite sequence of ascending + * integers, with a constant interval of time, `period` of your choosing + * between those emissions. The first emission happens after the specified + * `initialDelay`. The initial delay may be a {@link Date}. By default, this + * operator uses the `async` IScheduler to provide a notion of time, but you + * may pass any IScheduler to it. If `period` is not specified, the output + * Observable emits only one value, `0`. Otherwise, it emits an infinite + * sequence. + * + * @example Emits ascending numbers, one every second (1000ms), starting after 3 seconds + * var numbers = Rx.Observable.timer(3000, 1000); + * numbers.subscribe(x => console.log(x)); + * + * @example Emits one number after five seconds + * var numbers = Rx.Observable.timer(5000); + * numbers.subscribe(x => console.log(x)); + * + * @see {@link interval} + * @see {@link delay} + * + * @param {number|Date} initialDelay The initial delay time to wait before + * emitting the first value of `0`. + * @param {number} [period] The period of time between emissions of the + * subsequent numbers. + * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling + * the emission of values, and providing a notion of "time". + * @return {Observable} An Observable that emits a `0` after the + * `initialDelay` and ever increasing numbers after each `period` of time + * thereafter. + * @static true + * @name timer + * @owner Observable + */ + TimerObservable.create = function (initialDelay, period, scheduler) { + if (initialDelay === void 0) { initialDelay = 0; } + return new TimerObservable(initialDelay, period, scheduler); + }; + TimerObservable.dispatch = function (state) { + var index = state.index, period = state.period, subscriber = state.subscriber; + var action = this; + subscriber.next(index); + if (subscriber.closed) { + return; + } + else if (period === -1) { + return subscriber.complete(); + } + state.index = index + 1; + action.schedule(state, period); + }; + TimerObservable.prototype._subscribe = function (subscriber) { + var index = 0; + var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler; + return scheduler.schedule(TimerObservable.dispatch, dueTime, { + index: index, period: period, subscriber: subscriber + }); + }; + return TimerObservable; +}(Observable_1.Observable)); +exports.TimerObservable = TimerObservable; + +},{"../Observable":29,"../scheduler/async":212,"../util/isDate":228,"../util/isNumeric":230,"../util/isScheduler":233}],104:[function(require,module,exports){ "use strict"; var isScheduler_1 = require('../util/isScheduler'); var isArray_1 = require('../util/isArray'); var ArrayObservable_1 = require('./ArrayObservable'); -var combineLatest_1 = require('../operator/combineLatest'); +var combineLatest_1 = require('../operators/combineLatest'); /* tslint:enable:max-line-length */ /** * Combines multiple Observables to create an Observable whose values are @@ -7783,30 +8497,95 @@ var combineLatest_1 = require('../operator/combineLatest'); * * * `combineLatest` combines the values from all the Observables passed as - * arguments. This is done by subscribing to each Observable, in order, and - * collecting an array of each of the most recent values any time any of the - * input Observables emits, then either taking that array and passing it as - * arguments to an optional `project` function and emitting the return value of - * that, or just emitting the array of recent values directly if there is no - * `project` function. + * arguments. This is done by subscribing to each Observable in order and, + * whenever any Observable emits, collecting an array of the most recent + * values from each Observable. So if you pass `n` Observables to operator, + * returned Observable will always emit an array of `n` values, in order + * corresponding to order of passed Observables (value from the first Observable + * on the first place and so on). * - * @example Dynamically calculate the Body-Mass Index from an Observable of weight and one for height - * var weight = Rx.Observable.of(70, 72, 76, 79, 75); - * var height = Rx.Observable.of(1.76, 1.77, 1.78); - * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h)); - * bmi.subscribe(x => console.log('BMI is ' + x)); + * Static version of `combineLatest` accepts either an array of Observables + * or each Observable can be put directly as an argument. Note that array of + * Observables is good choice, if you don't know beforehand how many Observables + * you will combine. Passing empty array will result in Observable that + * completes immediately. * - * @see {@link combineAll} - * @see {@link merge} + * To ensure output array has always the same length, `combineLatest` will + * actually wait for all input Observables to emit at least once, + * before it starts emitting results. This means if some Observable emits + * values before other Observables started emitting, all that values but last + * will be lost. On the other hand, is some Observable does not emit value but + * completes, resulting Observable will complete at the same moment without + * emitting anything, since it will be now impossible to include value from + * completed Observable in resulting array. Also, if some input Observable does + * not emit any value and never completes, `combineLatest` will also never emit + * and never complete, since, again, it will wait for all streams to emit some + * value. + * + * If at least one Observable was passed to `combineLatest` and all passed Observables + * emitted something, resulting Observable will complete when all combined + * streams complete. So even if some Observable completes, result of + * `combineLatest` will still emit values when other Observables do. In case + * of completed Observable, its value from now on will always be the last + * emitted value. On the other hand, if any Observable errors, `combineLatest` + * will error immediately as well, and all other Observables will be unsubscribed. + * + * `combineLatest` accepts as optional parameter `project` function, which takes + * as arguments all values that would normally be emitted by resulting Observable. + * `project` can return any kind of value, which will be then emitted by Observable + * instead of default array. Note that `project` does not take as argument that array + * of values, but values themselves. That means default `project` can be imagined + * as function that takes all its arguments and puts them into an array. + * + * + * @example Combine two timer Observables + * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now + * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now + * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer); + * combinedTimers.subscribe(value => console.log(value)); + * // Logs + * // [0, 0] after 0.5s + * // [1, 0] after 1s + * // [1, 1] after 1.5s + * // [2, 1] after 2s + * + * + * @example Combine an array of Observables + * const observables = [1, 5, 10].map( + * n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds + * ); + * const combined = Rx.Observable.combineLatest(observables); + * combined.subscribe(value => console.log(value)); + * // Logs + * // [0, 0, 0] immediately + * // [1, 0, 0] after 1s + * // [1, 5, 0] after 5s + * // [1, 5, 10] after 10s + * + * + * @example Use project function to dynamically calculate the Body-Mass Index + * var weight = Rx.Observable.of(70, 72, 76, 79, 75); + * var height = Rx.Observable.of(1.76, 1.77, 1.78); + * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h)); + * bmi.subscribe(x => console.log('BMI is ' + x)); + * + * // With output to console: + * // BMI is 24.212293388429753 + * // BMI is 23.93948099205209 + * // BMI is 23.671253629592222 + * + * + * @see {@link combineAll} + * @see {@link merge} * @see {@link withLatestFrom} * - * @param {Observable} observable1 An input Observable to combine with the - * source Observable. - * @param {Observable} observable2 An input Observable to combine with the - * source Observable. More than one input Observables may be given as argument. + * @param {ObservableInput} observable1 An input Observable to combine with other Observables. + * @param {ObservableInput} observable2 An input Observable to combine with other Observables. + * More than one input Observables may be given as arguments + * or an array of Observables may be given as the first argument. * @param {function} [project] An optional function to project the values from * the combined latest values into a new value on the output Observable. - * @param {Scheduler} [scheduler=null] The Scheduler to use for subscribing to + * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to * each input Observable. * @return {Observable} An Observable of projected values from the most recent * values from each input Observable, or an array of the most recent values from @@ -7837,60 +8616,223 @@ function combineLatest() { } exports.combineLatest = combineLatest; -},{"../operator/combineLatest":102,"../util/isArray":148,"../util/isScheduler":152,"./ArrayObservable":79}],91:[function(require,module,exports){ +},{"../operators/combineLatest":164,"../util/isArray":226,"../util/isScheduler":233,"./ArrayObservable":93}],105:[function(require,module,exports){ +"use strict"; +var isScheduler_1 = require('../util/isScheduler'); +var of_1 = require('./of'); +var from_1 = require('./from'); +var concatAll_1 = require('../operators/concatAll'); +/* tslint:enable:max-line-length */ +/** + * Creates an output Observable which sequentially emits all values from given + * Observable and then moves on to the next. + * + * Concatenates multiple Observables together by + * sequentially emitting their values, one Observable after the other. + * + * + * + * `concat` joins multiple Observables together, by subscribing to them one at a time and + * merging their results into the output Observable. You can pass either an array of + * Observables, or put them directly as arguments. Passing an empty array will result + * in Observable that completes immediately. + * + * `concat` will subscribe to first input Observable and emit all its values, without + * changing or affecting them in any way. When that Observable completes, it will + * subscribe to then next Observable passed and, again, emit its values. This will be + * repeated, until the operator runs out of Observables. When last input Observable completes, + * `concat` will complete as well. At any given moment only one Observable passed to operator + * emits values. If you would like to emit values from passed Observables concurrently, check out + * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact, + * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`. + * + * Note that if some input Observable never completes, `concat` will also never complete + * and Observables following the one that did not complete will never be subscribed. On the other + * hand, if some Observable simply completes immediately after it is subscribed, it will be + * invisible for `concat`, which will just move on to the next Observable. + * + * If any Observable in chain errors, instead of passing control to the next Observable, + * `concat` will error immediately as well. Observables that would be subscribed after + * the one that emitted error, never will. + * + * If you pass to `concat` the same Observable many times, its stream of values + * will be "replayed" on every subscription, which means you can repeat given Observable + * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious, + * you can always use {@link repeat}. + * + * @example Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10 + * var timer = Rx.Observable.interval(1000).take(4); + * var sequence = Rx.Observable.range(1, 10); + * var result = Rx.Observable.concat(timer, sequence); + * result.subscribe(x => console.log(x)); + * + * // results in: + * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10 + * + * + * @example Concatenate an array of 3 Observables + * var timer1 = Rx.Observable.interval(1000).take(10); + * var timer2 = Rx.Observable.interval(2000).take(6); + * var timer3 = Rx.Observable.interval(500).take(10); + * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed + * result.subscribe(x => console.log(x)); + * + * // results in the following: + * // (Prints to console sequentially) + * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9 + * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5 + * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9 + * + * + * @example Concatenate the same Observable to repeat it + * const timer = Rx.Observable.interval(1000).take(2); + * + * Rx.Observable.concat(timer, timer) // concating the same Observable! + * .subscribe( + * value => console.log(value), + * err => {}, + * () => console.log('...and it is done!') + * ); + * + * // Logs: + * // 0 after 1s + * // 1 after 2s + * // 0 after 3s + * // 1 after 4s + * // "...and it is done!" also after 4s + * + * @see {@link concatAll} + * @see {@link concatMap} + * @see {@link concatMapTo} + * + * @param {ObservableInput} input1 An input Observable to concatenate with others. + * @param {ObservableInput} input2 An input Observable to concatenate with others. + * More than one input Observables may be given as argument. + * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each + * Observable subscription on. + * @return {Observable} All values of each passed Observable merged into a + * single Observable, in order, in serial fashion. + * @static true + * @name concat + * @owner Observable + */ +function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + if (observables.length === 1 || (observables.length === 2 && isScheduler_1.isScheduler(observables[1]))) { + return from_1.from(observables[0]); + } + return concatAll_1.concatAll()(of_1.of.apply(void 0, observables)); +} +exports.concat = concat; + +},{"../operators/concatAll":166,"../util/isScheduler":233,"./from":108,"./of":112}],106:[function(require,module,exports){ "use strict"; var DeferObservable_1 = require('./DeferObservable'); exports.defer = DeferObservable_1.DeferObservable.create; -},{"./DeferObservable":81}],92:[function(require,module,exports){ +},{"./DeferObservable":95}],107:[function(require,module,exports){ "use strict"; var EmptyObservable_1 = require('./EmptyObservable'); exports.empty = EmptyObservable_1.EmptyObservable.create; -},{"./EmptyObservable":82}],93:[function(require,module,exports){ +},{"./EmptyObservable":96}],108:[function(require,module,exports){ "use strict"; var FromObservable_1 = require('./FromObservable'); exports.from = FromObservable_1.FromObservable.create; -},{"./FromObservable":85}],94:[function(require,module,exports){ +},{"./FromObservable":99}],109:[function(require,module,exports){ "use strict"; var FromEventObservable_1 = require('./FromEventObservable'); exports.fromEvent = FromEventObservable_1.FromEventObservable.create; -},{"./FromEventObservable":84}],95:[function(require,module,exports){ +},{"./FromEventObservable":98}],110:[function(require,module,exports){ "use strict"; var PromiseObservable_1 = require('./PromiseObservable'); exports.fromPromise = PromiseObservable_1.PromiseObservable.create; -},{"./PromiseObservable":88}],96:[function(require,module,exports){ +},{"./PromiseObservable":101}],111:[function(require,module,exports){ "use strict"; var merge_1 = require('../operator/merge'); exports.merge = merge_1.mergeStatic; -},{"../operator/merge":114}],97:[function(require,module,exports){ +},{"../operator/merge":135}],112:[function(require,module,exports){ "use strict"; var ArrayObservable_1 = require('./ArrayObservable'); exports.of = ArrayObservable_1.ArrayObservable.of; -},{"./ArrayObservable":79}],98:[function(require,module,exports){ +},{"./ArrayObservable":93}],113:[function(require,module,exports){ "use strict"; var ErrorObservable_1 = require('./ErrorObservable'); exports._throw = ErrorObservable_1.ErrorObservable.create; -},{"./ErrorObservable":83}],99:[function(require,module,exports){ +},{"./ErrorObservable":97}],114:[function(require,module,exports){ +"use strict"; +var TimerObservable_1 = require('./TimerObservable'); +exports.timer = TimerObservable_1.TimerObservable.create; + +},{"./TimerObservable":103}],115:[function(require,module,exports){ "use strict"; -var zip_1 = require('../operator/zip'); +var zip_1 = require('../operators/zip'); exports.zip = zip_1.zipStatic; -},{"../operator/zip":132}],100:[function(require,module,exports){ +},{"../operators/zip":206}],116:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var async_1 = require('../scheduler/async'); +var auditTime_1 = require('../operators/auditTime'); +/** + * Ignores source values for `duration` milliseconds, then emits the most recent + * value from the source Observable, then repeats this process. + * + * When it sees a source values, it ignores that plus + * the next ones for `duration` milliseconds, and then it emits the most recent + * value from the source. + * + * + * + * `auditTime` is similar to `throttleTime`, but emits the last value from the + * silenced time window, instead of the first value. `auditTime` emits the most + * recent value from the source Observable on the output Observable as soon as + * its internal timer becomes disabled, and ignores source values while the + * timer is enabled. Initially, the timer is disabled. As soon as the first + * source value arrives, the timer is enabled. After `duration` milliseconds (or + * the time unit determined internally by the optional `scheduler`) has passed, + * the timer is disabled, then the most recent source value is emitted on the + * output Observable, and this process repeats for the next source value. + * Optionally takes a {@link IScheduler} for managing timers. + * + * @example Emit clicks at a rate of at most one click per second + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.auditTime(1000); + * result.subscribe(x => console.log(x)); + * + * @see {@link audit} + * @see {@link debounceTime} + * @see {@link delay} + * @see {@link sampleTime} + * @see {@link throttleTime} + * + * @param {number} duration Time to wait before emitting the most recent source + * value, measured in milliseconds or the time unit determined internally + * by the optional `scheduler`. + * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for + * managing the timers that handle the rate-limiting behavior. + * @return {Observable} An Observable that performs rate-limiting of + * emissions from the source Observable. + * @method auditTime + * @owner Observable + */ +function auditTime(duration, scheduler) { + if (scheduler === void 0) { scheduler = async_1.async; } + return auditTime_1.auditTime(duration, scheduler)(this); +} +exports.auditTime = auditTime; + +},{"../operators/auditTime":159,"../scheduler/async":212}],117:[function(require,module,exports){ +"use strict"; +var buffer_1 = require('../operators/buffer'); /** * Buffers the source Observable values until `closingNotifier` emits. * @@ -7924,119 +8866,172 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); * @owner Observable */ function buffer(closingNotifier) { - return this.lift(new BufferOperator(closingNotifier)); + return buffer_1.buffer(closingNotifier)(this); } exports.buffer = buffer; -var BufferOperator = (function () { - function BufferOperator(closingNotifier) { - this.closingNotifier = closingNotifier; - } - BufferOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new BufferSubscriber(subscriber, this.closingNotifier)); - }; - return BufferOperator; -}()); + +},{"../operators/buffer":160}],118:[function(require,module,exports){ +"use strict"; +var bufferCount_1 = require('../operators/bufferCount'); /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} + * Buffers the source Observable values until the size hits the maximum + * `bufferSize` given. + * + * Collects values from the past as an array, and emits + * that array only when its size reaches `bufferSize`. + * + * + * + * Buffers a number of values from the source Observable by `bufferSize` then + * emits the buffer and clears it, and starts a new buffer each + * `startBufferEvery` values. If `startBufferEvery` is not provided or is + * `null`, then new buffers are started immediately at the start of the source + * and when each buffer closes and is emitted. + * + * @example Emit the last two click events as an array + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var buffered = clicks.bufferCount(2); + * buffered.subscribe(x => console.log(x)); + * + * @example On every click, emit the last two click events as an array + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var buffered = clicks.bufferCount(2, 1); + * buffered.subscribe(x => console.log(x)); + * + * @see {@link buffer} + * @see {@link bufferTime} + * @see {@link bufferToggle} + * @see {@link bufferWhen} + * @see {@link pairwise} + * @see {@link windowCount} + * + * @param {number} bufferSize The maximum size of the buffer emitted. + * @param {number} [startBufferEvery] Interval at which to start a new buffer. + * For example if `startBufferEvery` is `2`, then a new buffer will be started + * on every other value from the source. A new buffer is started at the + * beginning of the source by default. + * @return {Observable} An Observable of arrays of buffered values. + * @method bufferCount + * @owner Observable */ -var BufferSubscriber = (function (_super) { - __extends(BufferSubscriber, _super); - function BufferSubscriber(destination, closingNotifier) { - _super.call(this, destination); - this.buffer = []; - this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier)); - } - BufferSubscriber.prototype._next = function (value) { - this.buffer.push(value); - }; - BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - var buffer = this.buffer; - this.buffer = []; - this.destination.next(buffer); - }; - return BufferSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); +function bufferCount(bufferSize, startBufferEvery) { + if (startBufferEvery === void 0) { startBufferEvery = null; } + return bufferCount_1.bufferCount(bufferSize, startBufferEvery)(this); +} +exports.bufferCount = bufferCount; -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],101:[function(require,module,exports){ +},{"../operators/bufferCount":161}],119:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var bufferWhen_1 = require('../operators/bufferWhen'); +/** + * Buffers the source Observable values, using a factory function of closing + * Observables to determine when to close, emit, and reset the buffer. + * + * Collects values from the past as an array. When it + * starts collecting values, it calls a function that returns an Observable that + * tells when to close the buffer and restart collecting. + * + * + * + * Opens a buffer immediately, then closes the buffer when the observable + * returned by calling `closingSelector` function emits a value. When it closes + * the buffer, it immediately opens a new buffer and repeats the process. + * + * @example Emit an array of the last clicks every [1-5] random seconds + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var buffered = clicks.bufferWhen(() => + * Rx.Observable.interval(1000 + Math.random() * 4000) + * ); + * buffered.subscribe(x => console.log(x)); + * + * @see {@link buffer} + * @see {@link bufferCount} + * @see {@link bufferTime} + * @see {@link bufferToggle} + * @see {@link windowWhen} + * + * @param {function(): Observable} closingSelector A function that takes no + * arguments and returns an Observable that signals buffer closure. + * @return {Observable} An observable of arrays of buffered values. + * @method bufferWhen + * @owner Observable + */ +function bufferWhen(closingSelector) { + return bufferWhen_1.bufferWhen(closingSelector)(this); +} +exports.bufferWhen = bufferWhen; + +},{"../operators/bufferWhen":162}],120:[function(require,module,exports){ +"use strict"; +var catchError_1 = require('../operators/catchError'); /** * Catches errors on the observable to be handled by returning a new observable or throwing an error. + * + * + * + * @example Continues with a different Observable when there's an error + * + * Observable.of(1, 2, 3, 4, 5) + * .map(n => { + * if (n == 4) { + * throw 'four!'; + * } + * return n; + * }) + * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V')) + * .subscribe(x => console.log(x)); + * // 1, 2, 3, I, II, III, IV, V + * + * @example Retries the caught source Observable again in case of error, similar to retry() operator + * + * Observable.of(1, 2, 3, 4, 5) + * .map(n => { + * if (n === 4) { + * throw 'four!'; + * } + * return n; + * }) + * .catch((err, caught) => caught) + * .take(30) + * .subscribe(x => console.log(x)); + * // 1, 2, 3, 1, 2, 3, ... + * + * @example Throws a new error when the source Observable throws an error + * + * Observable.of(1, 2, 3, 4, 5) + * .map(n => { + * if (n == 4) { + * throw 'four!'; + * } + * return n; + * }) + * .catch(err => { + * throw 'error in source. Details: ' + err; + * }) + * .subscribe( + * x => console.log(x), + * err => console.log(err) + * ); + * // 1, 2, 3, error in source. Details: four! + * * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable * is returned by the `selector` will be used to continue the observable chain. - * @return {Observable} an observable that originates from either the source or the observable returned by the + * @return {Observable} An observable that originates from either the source or the observable returned by the * catch `selector` function. * @method catch + * @name catch * @owner Observable */ function _catch(selector) { - var operator = new CatchOperator(selector); - var caught = this.lift(operator); - return (operator.caught = caught); + return catchError_1.catchError(selector)(this); } exports._catch = _catch; -var CatchOperator = (function () { - function CatchOperator(selector) { - this.selector = selector; - } - CatchOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); - }; - return CatchOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var CatchSubscriber = (function (_super) { - __extends(CatchSubscriber, _super); - function CatchSubscriber(destination, selector, caught) { - _super.call(this, destination); - this.selector = selector; - this.caught = caught; - } - // NOTE: overriding `error` instead of `_error` because we don't want - // to have this flag this subscriber as `isStopped`. - CatchSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var result = void 0; - try { - result = this.selector(err, this.caught); - } - catch (err) { - this.destination.error(err); - return; - } - this.unsubscribe(); - this.destination.remove(this); - subscribeToResult_1.subscribeToResult(this, result); - } - }; - return CatchSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],102:[function(require,module,exports){ +},{"../operators/catchError":163}],121:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var ArrayObservable_1 = require('../observable/ArrayObservable'); -var isArray_1 = require('../util/isArray'); -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); -var none = {}; +var combineLatest_1 = require('../operators/combineLatest'); +/* tslint:enable:max-line-length */ /** * Combines multiple Observables to create an Observable whose values are * calculated from the latest values of each of its input Observables. @@ -8061,11 +9056,16 @@ var none = {}; * var bmi = weight.combineLatest(height, (w, h) => w / (h * h)); * bmi.subscribe(x => console.log('BMI is ' + x)); * + * // With output to console: + * // BMI is 24.212293388429753 + * // BMI is 23.93948099205209 + * // BMI is 23.671253629592222 + * * @see {@link combineAll} * @see {@link merge} * @see {@link withLatestFrom} * - * @param {Observable} other An input Observable to combine with the source + * @param {ObservableInput} other An input Observable to combine with the source * Observable. More than one input Observables may be given as argument. * @param {function} [project] An optional function to project the values from * the combined latest values into a new value on the output Observable. @@ -8080,104 +9080,14 @@ function combineLatest() { for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } - var project = null; - if (typeof observables[observables.length - 1] === 'function') { - project = observables.pop(); - } - // if the first and only other argument besides the resultSelector is an array - // assume it's been called with `combineLatest([obs1, obs2, obs3], project)` - if (observables.length === 1 && isArray_1.isArray(observables[0])) { - observables = observables[0]; - } - observables.unshift(this); - return new ArrayObservable_1.ArrayObservable(observables).lift(new CombineLatestOperator(project)); + return combineLatest_1.combineLatest.apply(void 0, observables)(this); } exports.combineLatest = combineLatest; + +},{"../operators/combineLatest":164}],122:[function(require,module,exports){ +"use strict"; +var concat_1 = require('../operators/concat'); /* tslint:enable:max-line-length */ -var CombineLatestOperator = (function () { - function CombineLatestOperator(project) { - this.project = project; - } - CombineLatestOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new CombineLatestSubscriber(subscriber, this.project)); - }; - return CombineLatestOperator; -}()); -exports.CombineLatestOperator = CombineLatestOperator; -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var CombineLatestSubscriber = (function (_super) { - __extends(CombineLatestSubscriber, _super); - function CombineLatestSubscriber(destination, project) { - _super.call(this, destination); - this.project = project; - this.active = 0; - this.values = []; - this.observables = []; - } - CombineLatestSubscriber.prototype._next = function (observable) { - this.values.push(none); - this.observables.push(observable); - }; - CombineLatestSubscriber.prototype._complete = function () { - var observables = this.observables; - var len = observables.length; - if (len === 0) { - this.destination.complete(); - } - else { - this.active = len; - this.toRespond = len; - for (var i = 0; i < len; i++) { - var observable = observables[i]; - this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i)); - } - } - }; - CombineLatestSubscriber.prototype.notifyComplete = function (unused) { - if ((this.active -= 1) === 0) { - this.destination.complete(); - } - }; - CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - var values = this.values; - var oldVal = values[outerIndex]; - var toRespond = !this.toRespond - ? 0 - : oldVal === none ? --this.toRespond : this.toRespond; - values[outerIndex] = innerValue; - if (toRespond === 0) { - if (this.project) { - this._tryProject(values); - } - else { - this.destination.next(values.slice()); - } - } - }; - CombineLatestSubscriber.prototype._tryProject = function (values) { - var result; - try { - result = this.project.apply(this, values); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return CombineLatestSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -exports.CombineLatestSubscriber = CombineLatestSubscriber; - -},{"../OuterSubscriber":30,"../observable/ArrayObservable":79,"../util/isArray":148,"../util/subscribeToResult":154}],103:[function(require,module,exports){ -"use strict"; -var isScheduler_1 = require('../util/isScheduler'); -var ArrayObservable_1 = require('../observable/ArrayObservable'); -var mergeAll_1 = require('./mergeAll'); /** * Creates an output Observable which sequentially emits all values from every * given input Observable after the current Observable. @@ -8198,6 +9108,9 @@ var mergeAll_1 = require('./mergeAll'); * var result = timer.concat(sequence); * result.subscribe(x => console.log(x)); * + * // results in: + * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10 + * * @example Concatenate 3 Observables * var timer1 = Rx.Observable.interval(1000).take(10); * var timer2 = Rx.Observable.interval(2000).take(6); @@ -8205,13 +9118,19 @@ var mergeAll_1 = require('./mergeAll'); * var result = timer1.concat(timer2, timer3); * result.subscribe(x => console.log(x)); * + * // results in the following: + * // (Prints to console sequentially) + * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9 + * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5 + * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9 + * * @see {@link concatAll} * @see {@link concatMap} * @see {@link concatMapTo} * - * @param {Observable} other An input Observable to concatenate after the source + * @param {ObservableInput} other An input Observable to concatenate after the source * Observable. More than one input Observables may be given as argument. - * @param {Scheduler} [scheduler=null] An optional Scheduler to schedule each + * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each * Observable subscription on. * @return {Observable} All values of each passed Observable merged into a * single Observable, in order, in serial fashion. @@ -8223,74 +9142,70 @@ function concat() { for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } - return concatStatic.apply(void 0, [this].concat(observables)); + return concat_1.concat.apply(void 0, observables)(this); } exports.concat = concat; -/* tslint:enable:max-line-length */ + +},{"../operators/concat":165}],123:[function(require,module,exports){ +"use strict"; +var count_1 = require('../operators/count'); /** - * Creates an output Observable which sequentially emits all values from every - * given input Observable after the current Observable. + * Counts the number of emissions on the source and emits that number when the + * source completes. * - * Concatenates multiple Observables together by - * sequentially emitting their values, one Observable after the other. + * Tells how many values were emitted, when the source + * completes. * - * + * * - * Joins multiple Observables together by subscribing to them one at a time and - * merging their results into the output Observable. Will wait for each - * Observable to complete before moving on to the next. + * `count` transforms an Observable that emits values into an Observable that + * emits a single value that represents the number of values emitted by the + * source Observable. If the source Observable terminates with an error, `count` + * will pass this error notification along without emitting a value first. If + * the source Observable does not terminate at all, `count` will neither emit + * a value nor terminate. This operator takes an optional `predicate` function + * as argument, in which case the output emission will represent the number of + * source values that matched `true` with the `predicate`. * - * @example Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10 - * var timer = Rx.Observable.interval(1000).take(4); - * var sequence = Rx.Observable.range(1, 10); - * var result = Rx.Observable.concat(timer, sequence); + * @example Counts how many seconds have passed before the first click happened + * var seconds = Rx.Observable.interval(1000); + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var secondsBeforeClick = seconds.takeUntil(clicks); + * var result = secondsBeforeClick.count(); * result.subscribe(x => console.log(x)); * - * @example Concatenate 3 Observables - * var timer1 = Rx.Observable.interval(1000).take(10); - * var timer2 = Rx.Observable.interval(2000).take(6); - * var timer3 = Rx.Observable.interval(500).take(10); - * var result = Rx.Observable.concat(timer1, timer2, timer3); + * @example Counts how many odd numbers are there between 1 and 7 + * var numbers = Rx.Observable.range(1, 7); + * var result = numbers.count(i => i % 2 === 1); * result.subscribe(x => console.log(x)); * - * @see {@link concatAll} - * @see {@link concatMap} - * @see {@link concatMapTo} + * // Results in: + * // 4 * - * @param {Observable} input1 An input Observable to concatenate with others. - * @param {Observable} input2 An input Observable to concatenate with others. - * More than one input Observables may be given as argument. - * @param {Scheduler} [scheduler=null] An optional Scheduler to schedule each - * Observable subscription on. - * @return {Observable} All values of each passed Observable merged into a - * single Observable, in order, in serial fashion. - * @static true - * @name concat + * @see {@link max} + * @see {@link min} + * @see {@link reduce} + * + * @param {function(value: T, i: number, source: Observable): boolean} [predicate] A + * boolean function to select what values are to be counted. It is provided with + * arguments of: + * - `value`: the value from the source Observable. + * - `index`: the (zero-based) "index" of the value from the source Observable. + * - `source`: the source Observable instance itself. + * @return {Observable} An Observable of one number that represents the count as + * described above. + * @method count * @owner Observable */ -function concatStatic() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i - 0] = arguments[_i]; - } - var scheduler = null; - var args = observables; - if (isScheduler_1.isScheduler(args[observables.length - 1])) { - scheduler = args.pop(); - } - return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1)); +function count(predicate) { + return count_1.count(predicate)(this); } -exports.concatStatic = concatStatic; +exports.count = count; -},{"../observable/ArrayObservable":79,"../util/isScheduler":152,"./mergeAll":115}],104:[function(require,module,exports){ +},{"../operators/count":167}],124:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); var async_1 = require('../scheduler/async'); +var debounceTime_1 = require('../operators/debounceTime'); /** * Emits a value from the source Observable only after a particular time span * has passed without another source emission. @@ -8311,7 +9226,7 @@ var async_1 = require('../scheduler/async'); * This is a rate-limiting operator, because it is impossible for more than one * value to be emitted in any time window of duration `dueTime`, but it is also * a delay-like operator since output emissions do not occur at the same time as - * they did on the source Observable. Optionally takes a {@link Scheduler} for + * they did on the source Observable. Optionally takes a {@link IScheduler} for * managing timers. * * @example Emit the most recent click after a burst of clicks @@ -8329,7 +9244,7 @@ var async_1 = require('../scheduler/async'); * unit determined internally by the optional `scheduler`) for the window of * time required to wait for emission silence before emitting the most recent * source value. - * @param {Scheduler} [scheduler=async] The {@link Scheduler} to use for + * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for * managing the timers that handle the timeout for each value. * @return {Observable} An Observable that delays the emissions of the source * Observable by the specified `dueTime`, and may drop some values if they occur @@ -8339,242 +9254,170 @@ var async_1 = require('../scheduler/async'); */ function debounceTime(dueTime, scheduler) { if (scheduler === void 0) { scheduler = async_1.async; } - return this.lift(new DebounceTimeOperator(dueTime, scheduler)); + return debounceTime_1.debounceTime(dueTime, scheduler)(this); } exports.debounceTime = debounceTime; -var DebounceTimeOperator = (function () { - function DebounceTimeOperator(dueTime, scheduler) { - this.dueTime = dueTime; - this.scheduler = scheduler; - } - DebounceTimeOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler)); - }; - return DebounceTimeOperator; -}()); + +},{"../operators/debounceTime":168,"../scheduler/async":212}],125:[function(require,module,exports){ +"use strict"; +var async_1 = require('../scheduler/async'); +var delay_1 = require('../operators/delay'); /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} + * Delays the emission of items from the source Observable by a given timeout or + * until a given Date. + * + * Time shifts each item by some specified amount of + * milliseconds. + * + * + * + * If the delay argument is a Number, this operator time shifts the source + * Observable by that amount of time expressed in milliseconds. The relative + * time intervals between the values are preserved. + * + * If the delay argument is a Date, this operator time shifts the start of the + * Observable execution until the given date occurs. + * + * @example Delay each click by one second + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second + * delayedClicks.subscribe(x => console.log(x)); + * + * @example Delay all clicks until a future date happens + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var date = new Date('March 15, 2050 12:00:00'); // in the future + * var delayedClicks = clicks.delay(date); // click emitted only after that date + * delayedClicks.subscribe(x => console.log(x)); + * + * @see {@link debounceTime} + * @see {@link delayWhen} + * + * @param {number|Date} delay The delay duration in milliseconds (a `number`) or + * a `Date` until which the emission of the source items is delayed. + * @param {Scheduler} [scheduler=async] The IScheduler to use for + * managing the timers that handle the time-shift for each item. + * @return {Observable} An Observable that delays the emissions of the source + * Observable by the specified timeout or Date. + * @method delay + * @owner Observable */ -var DebounceTimeSubscriber = (function (_super) { - __extends(DebounceTimeSubscriber, _super); - function DebounceTimeSubscriber(destination, dueTime, scheduler) { - _super.call(this, destination); - this.dueTime = dueTime; - this.scheduler = scheduler; - this.debouncedSubscription = null; - this.lastValue = null; - this.hasValue = false; - } - DebounceTimeSubscriber.prototype._next = function (value) { - this.clearDebounce(); - this.lastValue = value; - this.hasValue = true; - this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this)); - }; - DebounceTimeSubscriber.prototype._complete = function () { - this.debouncedNext(); - this.destination.complete(); - }; - DebounceTimeSubscriber.prototype.debouncedNext = function () { - this.clearDebounce(); - if (this.hasValue) { - this.destination.next(this.lastValue); - this.lastValue = null; - this.hasValue = false; - } - }; - DebounceTimeSubscriber.prototype.clearDebounce = function () { - var debouncedSubscription = this.debouncedSubscription; - if (debouncedSubscription !== null) { - this.remove(debouncedSubscription); - debouncedSubscription.unsubscribe(); - this.debouncedSubscription = null; - } - }; - return DebounceTimeSubscriber; -}(Subscriber_1.Subscriber)); -function dispatchNext(subscriber) { - subscriber.debouncedNext(); +function delay(delay, scheduler) { + if (scheduler === void 0) { scheduler = async_1.async; } + return delay_1.delay(delay, scheduler)(this); } +exports.delay = delay; -},{"../Subscriber":35,"../scheduler/async":138}],105:[function(require,module,exports){ +},{"../operators/delay":170,"../scheduler/async":212}],126:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var distinct_1 = require('../operators/distinct'); /** * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items. - * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted. - * If a comparator function is not provided, an equality check is used by default. - * As the internal HashSet of this operator grows larger and larger, care should be taken in the domain of inputs this operator may see. - * An optional parameter is also provided such that an Observable can be provided to queue the internal HashSet to flush the values it holds. - * @param {function} [compare] optional comparison function called to test if an item is distinct from previous items in the source. - * @param {Observable} [flushes] optional Observable for flushing the internal HashSet of the operator. - * @return {Observable} an Observable that emits items from the source Observable with distinct values. + * + * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will + * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the + * source observable directly with an equality check against previous values. + * + * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking. + * + * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the + * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct` + * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so + * that the internal `Set` can be "flushed", basically clearing it of values. + * + * @example A simple example with numbers + * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1) + * .distinct() + * .subscribe(x => console.log(x)); // 1, 2, 3, 4 + * + * @example An example using a keySelector function + * interface Person { + * age: number, + * name: string + * } + * + * Observable.of( + * { age: 4, name: 'Foo'}, + * { age: 7, name: 'Bar'}, + * { age: 5, name: 'Foo'}) + * .distinct((p: Person) => p.name) + * .subscribe(x => console.log(x)); + * + * // displays: + * // { age: 4, name: 'Foo' } + * // { age: 7, name: 'Bar' } + * + * @see {@link distinctUntilChanged} + * @see {@link distinctUntilKeyChanged} + * + * @param {function} [keySelector] Optional function to select which value you want to check as distinct. + * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator. + * @return {Observable} An Observable that emits items from the source Observable with distinct values. * @method distinct * @owner Observable */ -function distinct(compare, flushes) { - return this.lift(new DistinctOperator(compare, flushes)); +function distinct(keySelector, flushes) { + return distinct_1.distinct(keySelector, flushes)(this); } exports.distinct = distinct; -var DistinctOperator = (function () { - function DistinctOperator(compare, flushes) { - this.compare = compare; - this.flushes = flushes; - } - DistinctOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new DistinctSubscriber(subscriber, this.compare, this.flushes)); - }; - return DistinctOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var DistinctSubscriber = (function (_super) { - __extends(DistinctSubscriber, _super); - function DistinctSubscriber(destination, compare, flushes) { - _super.call(this, destination); - this.values = []; - if (typeof compare === 'function') { - this.compare = compare; - } - if (flushes) { - this.add(subscribeToResult_1.subscribeToResult(this, flushes)); - } - } - DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values.length = 0; - }; - DistinctSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - DistinctSubscriber.prototype._next = function (value) { - var found = false; - var values = this.values; - var len = values.length; - try { - for (var i = 0; i < len; i++) { - if (this.compare(values[i], value)) { - found = true; - return; - } - } - } - catch (err) { - this.destination.error(err); - return; - } - this.values.push(value); - this.destination.next(value); - }; - DistinctSubscriber.prototype.compare = function (x, y) { - return x === y; - }; - return DistinctSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -exports.DistinctSubscriber = DistinctSubscriber; -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],106:[function(require,module,exports){ +},{"../operators/distinct":171}],127:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); -var tryCatch_1 = require('../util/tryCatch'); -var errorObject_1 = require('../util/errorObject'); +var distinctUntilChanged_1 = require('../operators/distinctUntilChanged'); +/* tslint:enable:max-line-length */ /** * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item. + * * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted. + * * If a comparator function is not provided, an equality check is used by default. - * @param {function} [compare] optional comparison function called to test if an item is distinct from the previous item in the source. - * @return {Observable} an Observable that emits items from the source Observable with distinct values. + * + * @example A simple example with numbers + * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4) + * .distinctUntilChanged() + * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4 + * + * @example An example using a compare function + * interface Person { + * age: number, + * name: string + * } + * + * Observable.of( + * { age: 4, name: 'Foo'}, + * { age: 7, name: 'Bar'}, + * { age: 5, name: 'Foo'}) + * { age: 6, name: 'Foo'}) + * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name) + * .subscribe(x => console.log(x)); + * + * // displays: + * // { age: 4, name: 'Foo' } + * // { age: 7, name: 'Bar' } + * // { age: 5, name: 'Foo' } + * + * @see {@link distinct} + * @see {@link distinctUntilKeyChanged} + * + * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source. + * @return {Observable} An Observable that emits items from the source Observable with distinct values. * @method distinctUntilChanged * @owner Observable */ function distinctUntilChanged(compare, keySelector) { - return this.lift(new DistinctUntilChangedOperator(compare, keySelector)); + return distinctUntilChanged_1.distinctUntilChanged(compare, keySelector)(this); } exports.distinctUntilChanged = distinctUntilChanged; -var DistinctUntilChangedOperator = (function () { - function DistinctUntilChangedOperator(compare, keySelector) { - this.compare = compare; - this.keySelector = keySelector; - } - DistinctUntilChangedOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector)); - }; - return DistinctUntilChangedOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var DistinctUntilChangedSubscriber = (function (_super) { - __extends(DistinctUntilChangedSubscriber, _super); - function DistinctUntilChangedSubscriber(destination, compare, keySelector) { - _super.call(this, destination); - this.keySelector = keySelector; - this.hasKey = false; - if (typeof compare === 'function') { - this.compare = compare; - } - } - DistinctUntilChangedSubscriber.prototype.compare = function (x, y) { - return x === y; - }; - DistinctUntilChangedSubscriber.prototype._next = function (value) { - var keySelector = this.keySelector; - var key = value; - if (keySelector) { - key = tryCatch_1.tryCatch(this.keySelector)(value); - if (key === errorObject_1.errorObject) { - return this.destination.error(errorObject_1.errorObject.e); - } - } - var result = false; - if (this.hasKey) { - result = tryCatch_1.tryCatch(this.compare)(this.key, key); - if (result === errorObject_1.errorObject) { - return this.destination.error(errorObject_1.errorObject.e); - } - } - else { - this.hasKey = true; - } - if (Boolean(result) === false) { - this.key = key; - this.destination.next(value); - } - }; - return DistinctUntilChangedSubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35,"../util/errorObject":147,"../util/tryCatch":156}],107:[function(require,module,exports){ +},{"../operators/distinctUntilChanged":172}],128:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); +var tap_1 = require('../operators/tap'); +/* tslint:enable:max-line-length */ /** * Perform a side effect for every emission on the source Observable, but return * an Observable that is identical to the source. * * Intercepts each emission on the source and runs a - * function, but returns an output which is identical to the source. + * function, but returns an output which is identical to the source as long as errors don't occur. * * * @@ -8592,7 +9435,7 @@ var Subscriber_1 = require('../Subscriber'); * Observer will never happen. `do` therefore simply spies on existing * execution, it does not trigger an execution to happen like `subscribe` does. * - * @example Map every every click to the clientX position of that click, while also logging the click event + * @example Map every click to the clientX position of that click, while also logging the click event * var clicks = Rx.Observable.fromEvent(document, 'click'); * var positions = clicks * .do(ev => console.log(ev)) @@ -8613,78 +9456,14 @@ var Subscriber_1 = require('../Subscriber'); * @owner Observable */ function _do(nextOrObserver, error, complete) { - return this.lift(new DoOperator(nextOrObserver, error, complete)); + return tap_1.tap(nextOrObserver, error, complete)(this); } exports._do = _do; -var DoOperator = (function () { - function DoOperator(nextOrObserver, error, complete) { - this.nextOrObserver = nextOrObserver; - this.error = error; - this.complete = complete; - } - DoOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); - }; - return DoOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var DoSubscriber = (function (_super) { - __extends(DoSubscriber, _super); - function DoSubscriber(destination, nextOrObserver, error, complete) { - _super.call(this, destination); - var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete); - safeSubscriber.syncErrorThrowable = true; - this.add(safeSubscriber); - this.safeSubscriber = safeSubscriber; - } - DoSubscriber.prototype._next = function (value) { - var safeSubscriber = this.safeSubscriber; - safeSubscriber.next(value); - if (safeSubscriber.syncErrorThrown) { - this.destination.error(safeSubscriber.syncErrorValue); - } - else { - this.destination.next(value); - } - }; - DoSubscriber.prototype._error = function (err) { - var safeSubscriber = this.safeSubscriber; - safeSubscriber.error(err); - if (safeSubscriber.syncErrorThrown) { - this.destination.error(safeSubscriber.syncErrorValue); - } - else { - this.destination.error(err); - } - }; - DoSubscriber.prototype._complete = function () { - var safeSubscriber = this.safeSubscriber; - safeSubscriber.complete(); - if (safeSubscriber.syncErrorThrown) { - this.destination.error(safeSubscriber.syncErrorValue); - } - else { - this.destination.complete(); - } - }; - return DoSubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35}],108:[function(require,module,exports){ +},{"../operators/tap":203}],129:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var tryCatch_1 = require('../util/tryCatch'); -var errorObject_1 = require('../util/errorObject'); -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var expand_1 = require('../operators/expand'); +/* tslint:enable:max-line-length */ /** * Recursively projects each source value to an Observable which is merged in * the output Observable. @@ -8721,7 +9500,7 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); * returns an Observable. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input * Observables being subscribed to concurrently. - * @param {Scheduler} [scheduler=null] The Scheduler to use for subscribing to + * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to * each projected inner Observable. * @return {Observable} An Observable that emits the source values and also * result of applying the projection function to each value emitted on the @@ -8734,105 +9513,14 @@ function expand(project, concurrent, scheduler) { if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } if (scheduler === void 0) { scheduler = undefined; } concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent; - return this.lift(new ExpandOperator(project, concurrent, scheduler)); + return expand_1.expand(project, concurrent, scheduler)(this); } exports.expand = expand; -var ExpandOperator = (function () { - function ExpandOperator(project, concurrent, scheduler) { - this.project = project; - this.concurrent = concurrent; - this.scheduler = scheduler; - } - ExpandOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler)); - }; - return ExpandOperator; -}()); -exports.ExpandOperator = ExpandOperator; -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var ExpandSubscriber = (function (_super) { - __extends(ExpandSubscriber, _super); - function ExpandSubscriber(destination, project, concurrent, scheduler) { - _super.call(this, destination); - this.project = project; - this.concurrent = concurrent; - this.scheduler = scheduler; - this.index = 0; - this.active = 0; - this.hasCompleted = false; - if (concurrent < Number.POSITIVE_INFINITY) { - this.buffer = []; - } - } - ExpandSubscriber.dispatch = function (arg) { - var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index; - subscriber.subscribeToProjection(result, value, index); - }; - ExpandSubscriber.prototype._next = function (value) { - var destination = this.destination; - if (destination.closed) { - this._complete(); - return; - } - var index = this.index++; - if (this.active < this.concurrent) { - destination.next(value); - var result = tryCatch_1.tryCatch(this.project)(value, index); - if (result === errorObject_1.errorObject) { - destination.error(errorObject_1.errorObject.e); - } - else if (!this.scheduler) { - this.subscribeToProjection(result, value, index); - } - else { - var state = { subscriber: this, result: result, value: value, index: index }; - this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state)); - } - } - else { - this.buffer.push(value); - } - }; - ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) { - this.active++; - this.add(subscribeToResult_1.subscribeToResult(this, result, value, index)); - }; - ExpandSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.hasCompleted && this.active === 0) { - this.destination.complete(); - } - }; - ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this._next(innerValue); - }; - ExpandSubscriber.prototype.notifyComplete = function (innerSub) { - var buffer = this.buffer; - this.remove(innerSub); - this.active--; - if (buffer && buffer.length > 0) { - this._next(buffer.shift()); - } - if (this.hasCompleted && this.active === 0) { - this.destination.complete(); - } - }; - return ExpandSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -exports.ExpandSubscriber = ExpandSubscriber; -},{"../OuterSubscriber":30,"../util/errorObject":147,"../util/subscribeToResult":154,"../util/tryCatch":156}],109:[function(require,module,exports){ +},{"../operators/expand":173}],130:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); +var filter_1 = require('../operators/filter'); +/* tslint:enable:max-line-length */ /** * Filter items emitted by the source Observable by only emitting those that * satisfy a specified predicate. @@ -8853,7 +9541,6 @@ var Subscriber_1 = require('../Subscriber'); * clicksOnDivs.subscribe(x => console.log(x)); * * @see {@link distinct} - * @see {@link distinctKey} * @see {@link distinctUntilChanged} * @see {@link distinctUntilKeyChanged} * @see {@link ignoreElements} @@ -8874,104 +9561,29 @@ var Subscriber_1 = require('../Subscriber'); * @owner Observable */ function filter(predicate, thisArg) { - return this.lift(new FilterOperator(predicate, thisArg)); + return filter_1.filter(predicate, thisArg)(this); } exports.filter = filter; -var FilterOperator = (function () { - function FilterOperator(predicate, thisArg) { - this.predicate = predicate; - this.thisArg = thisArg; - } - FilterOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); - }; - return FilterOperator; -}()); + +},{"../operators/filter":174}],131:[function(require,module,exports){ +"use strict"; +var finalize_1 = require('../operators/finalize'); /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var FilterSubscriber = (function (_super) { - __extends(FilterSubscriber, _super); - function FilterSubscriber(destination, predicate, thisArg) { - _super.call(this, destination); - this.predicate = predicate; - this.thisArg = thisArg; - this.count = 0; - this.predicate = predicate; - } - // the try catch block below is left specifically for - // optimization and perf reasons. a tryCatcher is not necessary here. - FilterSubscriber.prototype._next = function (value) { - var result; - try { - result = this.predicate.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this.destination.next(value); - } - }; - return FilterSubscriber; -}(Subscriber_1.Subscriber)); - -},{"../Subscriber":35}],110:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); -var Subscription_1 = require('../Subscription'); -/** - * Returns an Observable that mirrors the source Observable, but will call a specified function when - * the source terminates on complete or error. - * @param {function} callback function to be called when source terminates. - * @return {Observable} an Observable that mirrors the source, but will call the specified function on termination. - * @method finally - * @owner Observable + * Returns an Observable that mirrors the source Observable, but will call a specified function when + * the source terminates on complete or error. + * @param {function} callback Function to be called when source terminates. + * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination. + * @method finally + * @owner Observable */ function _finally(callback) { - return this.lift(new FinallyOperator(callback)); + return finalize_1.finalize(callback)(this); } exports._finally = _finally; -var FinallyOperator = (function () { - function FinallyOperator(callback) { - this.callback = callback; - } - FinallyOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new FinallySubscriber(subscriber, this.callback)); - }; - return FinallyOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var FinallySubscriber = (function (_super) { - __extends(FinallySubscriber, _super); - function FinallySubscriber(destination, callback) { - _super.call(this, destination); - this.add(new Subscription_1.Subscription(callback)); - } - return FinallySubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35,"../Subscription":36}],111:[function(require,module,exports){ +},{"../operators/finalize":175}],132:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); -var EmptyError_1 = require('../util/EmptyError'); +var first_1 = require('../operators/first'); /** * Emits only the first value (or the first value that meets some condition) * emitted by the source Observable. @@ -9016,111 +9628,20 @@ var EmptyError_1 = require('../util/EmptyError'); * - `index`: the "index" of the value from the source. * @param {R} [defaultValue] The default value emitted in case no valid value * was found on the source. - * @return {Observable} an Observable of the first item that matches the + * @return {Observable} An Observable of the first item that matches the * condition. * @method first * @owner Observable */ function first(predicate, resultSelector, defaultValue) { - return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this)); + return first_1.first(predicate, resultSelector, defaultValue)(this); } exports.first = first; -var FirstOperator = (function () { - function FirstOperator(predicate, resultSelector, defaultValue, source) { - this.predicate = predicate; - this.resultSelector = resultSelector; - this.defaultValue = defaultValue; - this.source = source; - } - FirstOperator.prototype.call = function (observer, source) { - return source._subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source)); - }; - return FirstOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var FirstSubscriber = (function (_super) { - __extends(FirstSubscriber, _super); - function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) { - _super.call(this, destination); - this.predicate = predicate; - this.resultSelector = resultSelector; - this.defaultValue = defaultValue; - this.source = source; - this.index = 0; - this.hasCompleted = false; - } - FirstSubscriber.prototype._next = function (value) { - var index = this.index++; - if (this.predicate) { - this._tryPredicate(value, index); - } - else { - this._emit(value, index); - } - }; - FirstSubscriber.prototype._tryPredicate = function (value, index) { - var result; - try { - result = this.predicate(value, index, this.source); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this._emit(value, index); - } - }; - FirstSubscriber.prototype._emit = function (value, index) { - if (this.resultSelector) { - this._tryResultSelector(value, index); - return; - } - this._emitFinal(value); - }; - FirstSubscriber.prototype._tryResultSelector = function (value, index) { - var result; - try { - result = this.resultSelector(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this._emitFinal(result); - }; - FirstSubscriber.prototype._emitFinal = function (value) { - var destination = this.destination; - destination.next(value); - destination.complete(); - this.hasCompleted = true; - }; - FirstSubscriber.prototype._complete = function () { - var destination = this.destination; - if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') { - destination.next(this.defaultValue); - destination.complete(); - } - else if (!this.hasCompleted) { - destination.error(new EmptyError_1.EmptyError); - } - }; - return FirstSubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35,"../util/EmptyError":144}],112:[function(require,module,exports){ +},{"../operators/first":176}],133:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); -var EmptyError_1 = require('../util/EmptyError'); +var last_1 = require('../operators/last'); +/* tslint:enable:max-line-length */ /** * Returns an Observable that emits only the last item emitted by the source Observable. * It optionally takes a predicate function as a parameter, in which case, rather than emitting @@ -9131,114 +9652,21 @@ var EmptyError_1 = require('../util/EmptyError'); * * @throws {EmptyError} Delivers an EmptyError to the Observer's `error` * callback if the Observable completes before any `next` notification was sent. - * @param {function} predicate - the condition any source emitted item has to satisfy. - * @return {Observable} an Observable that emits only the last item satisfying the given condition + * @param {function} predicate - The condition any source emitted item has to satisfy. + * @return {Observable} An Observable that emits only the last item satisfying the given condition * from the source, or an NoSuchElementException if no such items are emitted. * @throws - Throws if no items that match the predicate are emitted by the source Observable. * @method last * @owner Observable */ function last(predicate, resultSelector, defaultValue) { - return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this)); + return last_1.last(predicate, resultSelector, defaultValue)(this); } exports.last = last; -var LastOperator = (function () { - function LastOperator(predicate, resultSelector, defaultValue, source) { - this.predicate = predicate; - this.resultSelector = resultSelector; - this.defaultValue = defaultValue; - this.source = source; - } - LastOperator.prototype.call = function (observer, source) { - return source._subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source)); - }; - return LastOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var LastSubscriber = (function (_super) { - __extends(LastSubscriber, _super); - function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) { - _super.call(this, destination); - this.predicate = predicate; - this.resultSelector = resultSelector; - this.defaultValue = defaultValue; - this.source = source; - this.hasValue = false; - this.index = 0; - if (typeof defaultValue !== 'undefined') { - this.lastValue = defaultValue; - this.hasValue = true; - } - } - LastSubscriber.prototype._next = function (value) { - var index = this.index++; - if (this.predicate) { - this._tryPredicate(value, index); - } - else { - if (this.resultSelector) { - this._tryResultSelector(value, index); - return; - } - this.lastValue = value; - this.hasValue = true; - } - }; - LastSubscriber.prototype._tryPredicate = function (value, index) { - var result; - try { - result = this.predicate(value, index, this.source); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - if (this.resultSelector) { - this._tryResultSelector(value, index); - return; - } - this.lastValue = value; - this.hasValue = true; - } - }; - LastSubscriber.prototype._tryResultSelector = function (value, index) { - var result; - try { - result = this.resultSelector(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.lastValue = result; - this.hasValue = true; - }; - LastSubscriber.prototype._complete = function () { - var destination = this.destination; - if (this.hasValue) { - destination.next(this.lastValue); - destination.complete(); - } - else { - destination.error(new EmptyError_1.EmptyError); - } - }; - return LastSubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35,"../util/EmptyError":144}],113:[function(require,module,exports){ +},{"../operators/last":177}],134:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); +var map_1 = require('../operators/map'); /** * Applies a given `project` function to each value emitted by the source * Observable, and emits the resulting values as an Observable. @@ -9253,7 +9681,7 @@ var Subscriber_1 = require('../Subscriber'); * applies a projection to each value and emits that projection in the output * Observable. * - * @example Map every every click to the clientX position of that click + * @example Map every click to the clientX position of that click * var clicks = Rx.Observable.fromEvent(document, 'click'); * var positions = clicks.map(ev => ev.clientX); * positions.subscribe(x => console.log(x)); @@ -9273,57 +9701,16 @@ var Subscriber_1 = require('../Subscriber'); * @owner Observable */ function map(project, thisArg) { - if (typeof project !== 'function') { - throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); - } - return this.lift(new MapOperator(project, thisArg)); + return map_1.map(project, thisArg)(this); } exports.map = map; -var MapOperator = (function () { - function MapOperator(project, thisArg) { - this.project = project; - this.thisArg = thisArg; - } - MapOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); - }; - return MapOperator; -}()); -exports.MapOperator = MapOperator; -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var MapSubscriber = (function (_super) { - __extends(MapSubscriber, _super); - function MapSubscriber(destination, project, thisArg) { - _super.call(this, destination); - this.project = project; - this.count = 0; - this.thisArg = thisArg || this; - } - // NOTE: This looks unoptimized, but it's actually purposefully NOT - // using try/catch optimizations. - MapSubscriber.prototype._next = function (value) { - var result; - try { - result = this.project.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return MapSubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35}],114:[function(require,module,exports){ +},{"../operators/map":178}],135:[function(require,module,exports){ "use strict"; -var ArrayObservable_1 = require('../observable/ArrayObservable'); -var mergeAll_1 = require('./mergeAll'); -var isScheduler_1 = require('../util/isScheduler'); +var merge_1 = require('../operators/merge'); +var merge_2 = require('../operators/merge'); +exports.mergeStatic = merge_2.mergeStatic; +/* tslint:enable:max-line-length */ /** * Creates an output Observable which concurrently emits all values from every * given input Observable. @@ -9359,13 +9746,13 @@ var isScheduler_1 = require('../util/isScheduler'); * @see {@link mergeMapTo} * @see {@link mergeScan} * - * @param {Observable} other An input Observable to merge with the source + * @param {ObservableInput} other An input Observable to merge with the source * Observable. More than one input Observables may be given as argument. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input * Observables being subscribed to concurrently. - * @param {Scheduler} [scheduler=null] The Scheduler to use for managing + * @param {Scheduler} [scheduler=null] The IScheduler to use for managing * concurrency of input Observables. - * @return {Observable} an Observable that emits items that are the result of + * @return {Observable} An Observable that emits items that are the result of * every input Observable. * @method merge * @owner Observable @@ -9375,90 +9762,13 @@ function merge() { for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } - observables.unshift(this); - return mergeStatic.apply(this, observables); + return merge_1.merge.apply(void 0, observables)(this); } exports.merge = merge; -/* tslint:enable:max-line-length */ -/** - * Creates an output Observable which concurrently emits all values from every - * given input Observable. - * - * Flattens multiple Observables together by blending - * their values into one Observable. - * - * - * - * `merge` subscribes to each given input Observable (as arguments), and simply - * forwards (without doing any transformation) all the values from all the input - * Observables to the output Observable. The output Observable only completes - * once all input Observables have completed. Any error delivered by an input - * Observable will be immediately emitted on the output Observable. - * - * @example Merge together two Observables: 1s interval and clicks - * var clicks = Rx.Observable.fromEvent(document, 'click'); - * var timer = Rx.Observable.interval(1000); - * var clicksOrTimer = Rx.Observable.merge(clicks, timer); - * clicksOrTimer.subscribe(x => console.log(x)); - * - * @example Merge together 3 Observables, but only 2 run concurrently - * var timer1 = Rx.Observable.interval(1000).take(10); - * var timer2 = Rx.Observable.interval(2000).take(6); - * var timer3 = Rx.Observable.interval(500).take(10); - * var concurrent = 2; // the argument - * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent); - * merged.subscribe(x => console.log(x)); - * - * @see {@link mergeAll} - * @see {@link mergeMap} - * @see {@link mergeMapTo} - * @see {@link mergeScan} - * - * @param {Observable} input1 An input Observable to merge with others. - * @param {Observable} input2 An input Observable to merge with others. - * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input - * Observables being subscribed to concurrently. - * @param {Scheduler} [scheduler=null] The Scheduler to use for managing - * concurrency of input Observables. - * @return {Observable} an Observable that emits items that are the result of - * every input Observable. - * @static true - * @name merge - * @owner Observable - */ -function mergeStatic() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i - 0] = arguments[_i]; - } - var concurrent = Number.POSITIVE_INFINITY; - var scheduler = null; - var last = observables[observables.length - 1]; - if (isScheduler_1.isScheduler(last)) { - scheduler = observables.pop(); - if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') { - concurrent = observables.pop(); - } - } - else if (typeof last === 'number') { - concurrent = observables.pop(); - } - if (observables.length === 1) { - return observables[0]; - } - return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent)); -} -exports.mergeStatic = mergeStatic; -},{"../observable/ArrayObservable":79,"../util/isScheduler":152,"./mergeAll":115}],115:[function(require,module,exports){ +},{"../operators/merge":179}],136:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var mergeAll_1 = require('../operators/mergeAll'); /** * Converts a higher-order Observable into a first-order Observable which * concurrently delivers all values that are emitted on the inner Observables. @@ -9505,72 +9815,14 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); */ function mergeAll(concurrent) { if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } - return this.lift(new MergeAllOperator(concurrent)); + return mergeAll_1.mergeAll(concurrent)(this); } exports.mergeAll = mergeAll; -var MergeAllOperator = (function () { - function MergeAllOperator(concurrent) { - this.concurrent = concurrent; - } - MergeAllOperator.prototype.call = function (observer, source) { - return source._subscribe(new MergeAllSubscriber(observer, this.concurrent)); - }; - return MergeAllOperator; -}()); -exports.MergeAllOperator = MergeAllOperator; -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var MergeAllSubscriber = (function (_super) { - __extends(MergeAllSubscriber, _super); - function MergeAllSubscriber(destination, concurrent) { - _super.call(this, destination); - this.concurrent = concurrent; - this.hasCompleted = false; - this.buffer = []; - this.active = 0; - } - MergeAllSubscriber.prototype._next = function (observable) { - if (this.active < this.concurrent) { - this.active++; - this.add(subscribeToResult_1.subscribeToResult(this, observable)); - } - else { - this.buffer.push(observable); - } - }; - MergeAllSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - this.destination.complete(); - } - }; - MergeAllSubscriber.prototype.notifyComplete = function (innerSub) { - var buffer = this.buffer; - this.remove(innerSub); - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - this.destination.complete(); - } - }; - return MergeAllSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -exports.MergeAllSubscriber = MergeAllSubscriber; -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],116:[function(require,module,exports){ +},{"../operators/mergeAll":180}],137:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var subscribeToResult_1 = require('../util/subscribeToResult'); -var OuterSubscriber_1 = require('../OuterSubscriber'); +var mergeMap_1 = require('../operators/mergeMap'); +/* tslint:enable:max-line-length */ /** * Projects each source value to an Observable which is merged in the output * Observable. @@ -9592,6 +9844,15 @@ var OuterSubscriber_1 = require('../OuterSubscriber'); * ); * result.subscribe(x => console.log(x)); * + * // Results in the following: + * // a0 + * // b0 + * // c0 + * // a1 + * // b1 + * // c1 + * // continues to list a,b,c with respective ascending integers + * * @see {@link concatMap} * @see {@link exhaustMap} * @see {@link merge} @@ -9600,7 +9861,7 @@ var OuterSubscriber_1 = require('../OuterSubscriber'); * @see {@link mergeScan} * @see {@link switchMap} * - * @param {function(value: T, ?index: number): Observable} project A function + * @param {function(value: T, ?index: number): ObservableInput} project A function * that, when applied to an item emitted by the source Observable, returns an * Observable. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector] @@ -9622,237 +9883,19 @@ var OuterSubscriber_1 = require('../OuterSubscriber'); */ function mergeMap(project, resultSelector, concurrent) { if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } - if (typeof resultSelector === 'number') { - concurrent = resultSelector; - resultSelector = null; - } - return this.lift(new MergeMapOperator(project, resultSelector, concurrent)); + return mergeMap_1.mergeMap(project, resultSelector, concurrent)(this); } exports.mergeMap = mergeMap; -var MergeMapOperator = (function () { - function MergeMapOperator(project, resultSelector, concurrent) { - if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } - this.project = project; - this.resultSelector = resultSelector; - this.concurrent = concurrent; - } - MergeMapOperator.prototype.call = function (observer, source) { - return source._subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent)); - }; - return MergeMapOperator; -}()); -exports.MergeMapOperator = MergeMapOperator; -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var MergeMapSubscriber = (function (_super) { - __extends(MergeMapSubscriber, _super); - function MergeMapSubscriber(destination, project, resultSelector, concurrent) { - if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } - _super.call(this, destination); - this.project = project; - this.resultSelector = resultSelector; - this.concurrent = concurrent; - this.hasCompleted = false; - this.buffer = []; - this.active = 0; - this.index = 0; - } - MergeMapSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - this._tryNext(value); - } - else { - this.buffer.push(value); - } - }; - MergeMapSubscriber.prototype._tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.active++; - this._innerSub(result, value, index); - }; - MergeMapSubscriber.prototype._innerSub = function (ish, value, index) { - this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index)); - }; - MergeMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - this.destination.complete(); - } - }; - MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - if (this.resultSelector) { - this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex); - } - else { - this.destination.next(innerValue); - } - }; - MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) { - var result; - try { - result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - MergeMapSubscriber.prototype.notifyComplete = function (innerSub) { - var buffer = this.buffer; - this.remove(innerSub); - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - this.destination.complete(); - } - }; - return MergeMapSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -exports.MergeMapSubscriber = MergeMapSubscriber; -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],117:[function(require,module,exports){ +},{"../operators/mergeMap":181}],138:[function(require,module,exports){ "use strict"; -var MulticastObservable_1 = require('../observable/MulticastObservable'); -var ConnectableObservable_1 = require('../observable/ConnectableObservable'); +var pairwise_1 = require('../operators/pairwise'); /** - * Returns an Observable that emits the results of invoking a specified selector on items - * emitted by a ConnectableObservable that shares a single subscription to the underlying stream. + * Groups pairs of consecutive emissions together and emits them as an array of + * two values. * - * - * - * @param {Function|Subject} Factory function to create an intermediate subject through - * which the source sequence's elements will be multicast to the selector function - * or Subject to push source elements into. - * @param {Function} Optional selector function that can use the multicasted source stream - * as many times as needed, without causing multiple subscriptions to the source stream. - * Subscribers to the given source will receive all notifications of the source from the - * time of the subscription forward. - * @return {Observable} an Observable that emits the results of invoking the selector - * on the items emitted by a `ConnectableObservable` that shares a single subscription to - * the underlying stream. - * @method multicast - * @owner Observable - */ -function multicast(subjectOrSubjectFactory, selector) { - var subjectFactory; - if (typeof subjectOrSubjectFactory === 'function') { - subjectFactory = subjectOrSubjectFactory; - } - else { - subjectFactory = function subjectFactory() { - return subjectOrSubjectFactory; - }; - } - return !selector ? - new ConnectableObservable_1.ConnectableObservable(this, subjectFactory) : - new MulticastObservable_1.MulticastObservable(this, subjectFactory, selector); -} -exports.multicast = multicast; - -},{"../observable/ConnectableObservable":80,"../observable/MulticastObservable":87}],118:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); -var Notification_1 = require('../Notification'); -/** - * @see {@link Notification} - * - * @param scheduler - * @param delay - * @return {Observable|WebSocketSubject|Observable} - * @method observeOn - * @owner Observable - */ -function observeOn(scheduler, delay) { - if (delay === void 0) { delay = 0; } - return this.lift(new ObserveOnOperator(scheduler, delay)); -} -exports.observeOn = observeOn; -var ObserveOnOperator = (function () { - function ObserveOnOperator(scheduler, delay) { - if (delay === void 0) { delay = 0; } - this.scheduler = scheduler; - this.delay = delay; - } - ObserveOnOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay)); - }; - return ObserveOnOperator; -}()); -exports.ObserveOnOperator = ObserveOnOperator; -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var ObserveOnSubscriber = (function (_super) { - __extends(ObserveOnSubscriber, _super); - function ObserveOnSubscriber(destination, scheduler, delay) { - if (delay === void 0) { delay = 0; } - _super.call(this, destination); - this.scheduler = scheduler; - this.delay = delay; - } - ObserveOnSubscriber.dispatch = function (arg) { - var notification = arg.notification, destination = arg.destination; - notification.observe(destination); - }; - ObserveOnSubscriber.prototype.scheduleMessage = function (notification) { - this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination))); - }; - ObserveOnSubscriber.prototype._next = function (value) { - this.scheduleMessage(Notification_1.Notification.createNext(value)); - }; - ObserveOnSubscriber.prototype._error = function (err) { - this.scheduleMessage(Notification_1.Notification.createError(err)); - }; - ObserveOnSubscriber.prototype._complete = function () { - this.scheduleMessage(Notification_1.Notification.createComplete()); - }; - return ObserveOnSubscriber; -}(Subscriber_1.Subscriber)); -exports.ObserveOnSubscriber = ObserveOnSubscriber; -var ObserveOnMessage = (function () { - function ObserveOnMessage(notification, destination) { - this.notification = notification; - this.destination = destination; - } - return ObserveOnMessage; -}()); -exports.ObserveOnMessage = ObserveOnMessage; - -},{"../Notification":27,"../Subscriber":35}],119:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); -/** - * Groups pairs of consecutive emissions together and emits them as an array of - * two values. - * - * Puts the current value and previous value together as - * an array, and emits that. + * Puts the current value and previous value together as + * an array, and emits that. * * * @@ -9883,43 +9926,13 @@ var Subscriber_1 = require('../Subscriber'); * @owner Observable */ function pairwise() { - return this.lift(new PairwiseOperator()); + return pairwise_1.pairwise()(this); } exports.pairwise = pairwise; -var PairwiseOperator = (function () { - function PairwiseOperator() { - } - PairwiseOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new PairwiseSubscriber(subscriber)); - }; - return PairwiseOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var PairwiseSubscriber = (function (_super) { - __extends(PairwiseSubscriber, _super); - function PairwiseSubscriber(destination) { - _super.call(this, destination); - this.hasPrev = false; - } - PairwiseSubscriber.prototype._next = function (value) { - if (this.hasPrev) { - this.destination.next([this.prev, value]); - } - else { - this.hasPrev = true; - } - this.prev = value; - }; - return PairwiseSubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35}],120:[function(require,module,exports){ +},{"../operators/pairwise":184}],139:[function(require,module,exports){ "use strict"; -var map_1 = require('./map'); +var pluck_1 = require('../operators/pluck'); /** * Maps each source value (an object) to its specified nested property. * @@ -9933,7 +9946,7 @@ var map_1 = require('./map'); * Observable. If a property can't be resolved, it will return `undefined` for * that value. * - * @example Map every every click to the tagName of the clicked target element + * @example Map every click to the tagName of the clicked target element * var clicks = Rx.Observable.fromEvent(document, 'click'); * var tagNames = clicks.pluck('target', 'tagName'); * tagNames.subscribe(x => console.log(x)); @@ -9942,8 +9955,7 @@ var map_1 = require('./map'); * * @param {...string} properties The nested properties to pluck from each source * value (an object). - * @return {Observable} Returns a new Observable of property values from the - * source values. + * @return {Observable} A new Observable of property values from the source values. * @method pluck * @owner Observable */ @@ -9952,80 +9964,182 @@ function pluck() { for (var _i = 0; _i < arguments.length; _i++) { properties[_i - 0] = arguments[_i]; } - var length = properties.length; - if (length === 0) { - throw new Error('list of properties cannot be empty.'); - } - return map_1.map.call(this, plucker(properties, length)); + return pluck_1.pluck.apply(void 0, properties)(this); } exports.pluck = pluck; -function plucker(props, length) { - var mapper = function (x) { - var currentProp = x; - for (var i = 0; i < length; i++) { - var p = currentProp[props[i]]; - if (typeof p !== 'undefined') { - currentProp = p; - } - else { - return undefined; - } - } - return currentProp; - }; - return mapper; -} -},{"./map":113}],121:[function(require,module,exports){ +},{"../operators/pluck":185}],140:[function(require,module,exports){ "use strict"; -var Subject_1 = require('../Subject'); -var multicast_1 = require('./multicast'); +var publish_1 = require('../operators/publish'); +/* tslint:enable:max-line-length */ /** * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called * before it begins emitting items to those Observers that have subscribed to it. * * * - * @param {Function} Optional selector function which can use the multicasted source sequence as many times as needed, - * without causing multiple subscriptions to the source sequence. + * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times + * as needed, without causing multiple subscriptions to the source sequence. * Subscribers to the given source will receive all notifications of the source from the time of the subscription on. - * @return a ConnectableObservable that upon connection causes the source Observable to emit items to its Observers. + * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers. * @method publish * @owner Observable */ function publish(selector) { - return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) : - multicast_1.multicast.call(this, new Subject_1.Subject()); + return publish_1.publish(selector)(this); } exports.publish = publish; -},{"../Subject":33,"./multicast":117}],122:[function(require,module,exports){ +},{"../operators/publish":186}],141:[function(require,module,exports){ "use strict"; -var ReplaySubject_1 = require('../ReplaySubject'); -var multicast_1 = require('./multicast'); +var publishReplay_1 = require('../operators/publishReplay'); +/* tslint:enable:max-line-length */ /** * @param bufferSize * @param windowTime + * @param selectorOrScheduler * @param scheduler - * @return {ConnectableObservable} + * @return {Observable | ConnectableObservable} * @method publishReplay * @owner Observable */ -function publishReplay(bufferSize, windowTime, scheduler) { - if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; } - if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; } - return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler)); +function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) { + return publishReplay_1.publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler)(this); } exports.publishReplay = publishReplay; -},{"../ReplaySubject":31,"./multicast":117}],123:[function(require,module,exports){ +},{"../operators/publishReplay":187}],142:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); +var reduce_1 = require('../operators/reduce'); +/* tslint:enable:max-line-length */ +/** + * Applies an accumulator function over the source Observable, and returns the + * accumulated result when the source completes, given an optional seed value. + * + * Combines together all values emitted on the source, + * using an accumulator function that knows how to join a new source value into + * the accumulation from the past. + * + * + * + * Like + * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce), + * `reduce` applies an `accumulator` function against an accumulation and each + * value of the source Observable (from the past) to reduce it to a single + * value, emitted on the output Observable. Note that `reduce` will only emit + * one value, only when the source Observable completes. It is equivalent to + * applying operator {@link scan} followed by operator {@link last}. + * + * Returns an Observable that applies a specified `accumulator` function to each + * item emitted by the source Observable. If a `seed` value is specified, then + * that value will be used as the initial value for the accumulator. If no seed + * value is specified, the first item of the source is used as the seed. + * + * @example Count the number of click events that happened in 5 seconds + * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click') + * .takeUntil(Rx.Observable.interval(5000)); + * var ones = clicksInFiveSeconds.mapTo(1); + * var seed = 0; + * var count = ones.reduce((acc, one) => acc + one, seed); + * count.subscribe(x => console.log(x)); + * + * @see {@link count} + * @see {@link expand} + * @see {@link mergeScan} + * @see {@link scan} + * + * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function + * called on each source value. + * @param {R} [seed] The initial accumulation value. + * @return {Observable} An Observable that emits a single value that is the + * result of accumulating the values emitted by the source Observable. + * @method reduce + * @owner Observable + */ +function reduce(accumulator, seed) { + // providing a seed of `undefined` *should* be valid and trigger + // hasSeed! so don't use `seed !== undefined` checks! + // For this reason, we have to check it here at the original call site + // otherwise inside Operator/Subscriber we won't know if `undefined` + // means they didn't provide anything or if they literally provided `undefined` + if (arguments.length >= 2) { + return reduce_1.reduce(accumulator, seed)(this); + } + return reduce_1.reduce(accumulator)(this); +} +exports.reduce = reduce; + +},{"../operators/reduce":188}],143:[function(require,module,exports){ +"use strict"; +var retry_1 = require('../operators/retry'); +/** + * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable + * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given + * as a number parameter) rather than propagating the `error` call. + * + * + * + * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted + * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second + * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications + * would be: [1, 2, 1, 2, 3, 4, 5, `complete`]. + * @param {number} count - Number of retry attempts before failing. + * @return {Observable} The source Observable modified with the retry logic. + * @method retry + * @owner Observable + */ +function retry(count) { + if (count === void 0) { count = -1; } + return retry_1.retry(count)(this); +} +exports.retry = retry; + +},{"../operators/retry":190}],144:[function(require,module,exports){ +"use strict"; +var sample_1 = require('../operators/sample'); +/** + * Emits the most recently emitted value from the source Observable whenever + * another Observable, the `notifier`, emits. + * + * It's like {@link sampleTime}, but samples whenever + * the `notifier` Observable emits something. + * + * + * + * Whenever the `notifier` Observable emits a value or completes, `sample` + * looks at the source Observable and emits whichever value it has most recently + * emitted since the previous sampling, unless the source has not emitted + * anything since the previous sampling. The `notifier` is subscribed to as soon + * as the output Observable is subscribed. + * + * @example On every click, sample the most recent "seconds" timer + * var seconds = Rx.Observable.interval(1000); + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = seconds.sample(clicks); + * result.subscribe(x => console.log(x)); + * + * @see {@link audit} + * @see {@link debounce} + * @see {@link sampleTime} + * @see {@link throttle} + * + * @param {Observable} notifier The Observable to use for sampling the + * source Observable. + * @return {Observable} An Observable that emits the results of sampling the + * values emitted by the source Observable whenever the notifier Observable + * emits value or completes. + * @method sample + * @owner Observable + */ +function sample(notifier) { + return sample_1.sample(notifier)(this); +} +exports.sample = sample; + +},{"../operators/sample":191}],145:[function(require,module,exports){ +"use strict"; +var scan_1 = require('../operators/scan'); +/* tslint:enable:max-line-length */ /** * Applies an accumulator function over the source Observable, and returns each * intermediate result, with an optional seed value. @@ -10064,233 +10178,111 @@ var Subscriber_1 = require('../Subscriber'); * @owner Observable */ function scan(accumulator, seed) { - return this.lift(new ScanOperator(accumulator, seed)); + if (arguments.length >= 2) { + return scan_1.scan(accumulator, seed)(this); + } + return scan_1.scan(accumulator)(this); } exports.scan = scan; -var ScanOperator = (function () { - function ScanOperator(accumulator, seed) { - this.accumulator = accumulator; - this.seed = seed; - } - ScanOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed)); - }; - return ScanOperator; -}()); + +},{"../operators/scan":192}],146:[function(require,module,exports){ +"use strict"; +var share_1 = require('../operators/share'); /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var ScanSubscriber = (function (_super) { - __extends(ScanSubscriber, _super); - function ScanSubscriber(destination, accumulator, seed) { - _super.call(this, destination); - this.accumulator = accumulator; - this.index = 0; - this.accumulatorSet = false; - this.seed = seed; - this.accumulatorSet = typeof seed !== 'undefined'; - } - Object.defineProperty(ScanSubscriber.prototype, "seed", { - get: function () { - return this._seed; - }, - set: function (value) { - this.accumulatorSet = true; - this._seed = value; - }, - enumerable: true, - configurable: true - }); - ScanSubscriber.prototype._next = function (value) { - if (!this.accumulatorSet) { - this.seed = value; - this.destination.next(value); - } - else { - return this._tryNext(value); - } - }; - ScanSubscriber.prototype._tryNext = function (value) { - var index = this.index++; - var result; - try { - result = this.accumulator(this.seed, value, index); - } - catch (err) { - this.destination.error(err); - } - this.seed = result; - this.destination.next(result); - }; - return ScanSubscriber; -}(Subscriber_1.Subscriber)); - -},{"../Subscriber":35}],124:[function(require,module,exports){ -"use strict"; -var multicast_1 = require('./multicast'); -var Subject_1 = require('../Subject'); -function shareSubjectFactory() { - return new Subject_1.Subject(); -} -/** - * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one - * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will - * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`. - * This is an alias for .publish().refCount(). - * - * - * - * @return {Observable} an Observable that upon connection causes the source Observable to emit items to its Observers - * @method share - * @owner Observable + * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one + * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will + * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`. + * + * This behaves similarly to .publish().refCount(), with a behavior difference when the source observable emits complete. + * .publish().refCount() will not resubscribe to the original source, however .share() will resubscribe to the original source. + * Observable.of("test").publish().refCount() will not re-emit "test" on new subscriptions, Observable.of("test").share() will + * re-emit "test" to new subscriptions. + * + * + * + * @return {Observable} An Observable that upon connection causes the source Observable to emit items to its Observers. + * @method share + * @owner Observable */ function share() { - return multicast_1.multicast.call(this, shareSubjectFactory).refCount(); + return share_1.share()(this); } exports.share = share; ; -},{"../Subject":33,"./multicast":117}],125:[function(require,module,exports){ +},{"../operators/share":193}],147:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); +var skip_1 = require('../operators/skip'); /** - * Returns an Observable that skips `n` items emitted by an Observable. + * Returns an Observable that skips the first `count` items emitted by the source Observable. * * * - * @param {Number} the `n` of times, items emitted by source Observable should be skipped. - * @return {Observable} an Observable that skips values emitted by the source Observable. + * @param {Number} count - The number of times, items emitted by source Observable should be skipped. + * @return {Observable} An Observable that skips values emitted by the source Observable. * * @method skip * @owner Observable */ -function skip(total) { - return this.lift(new SkipOperator(total)); +function skip(count) { + return skip_1.skip(count)(this); } exports.skip = skip; -var SkipOperator = (function () { - function SkipOperator(total) { - this.total = total; - } - SkipOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new SkipSubscriber(subscriber, this.total)); - }; - return SkipOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var SkipSubscriber = (function (_super) { - __extends(SkipSubscriber, _super); - function SkipSubscriber(destination, total) { - _super.call(this, destination); - this.total = total; - this.count = 0; - } - SkipSubscriber.prototype._next = function (x) { - if (++this.count > this.total) { - this.destination.next(x); - } - }; - return SkipSubscriber; -}(Subscriber_1.Subscriber)); -},{"../Subscriber":35}],126:[function(require,module,exports){ +},{"../operators/skip":194}],148:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var skipUntil_1 = require('../operators/skipUntil'); /** * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item. * * * - * @param {Observable} the second Observable that has to emit an item before the source Observable's elements begin to + * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to * be mirrored by the resulting Observable. - * @return {Observable} an Observable that skips items from the source Observable until the second Observable emits + * @return {Observable} An Observable that skips items from the source Observable until the second Observable emits * an item, then emits the remaining items. * @method skipUntil * @owner Observable */ function skipUntil(notifier) { - return this.lift(new SkipUntilOperator(notifier)); + return skipUntil_1.skipUntil(notifier)(this); } exports.skipUntil = skipUntil; -var SkipUntilOperator = (function () { - function SkipUntilOperator(notifier) { - this.notifier = notifier; - } - SkipUntilOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new SkipUntilSubscriber(subscriber, this.notifier)); - }; - return SkipUntilOperator; -}()); + +},{"../operators/skipUntil":195}],149:[function(require,module,exports){ +"use strict"; +var skipWhile_1 = require('../operators/skipWhile'); /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} + * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds + * true, but emits all further source items as soon as the condition becomes false. + * + * + * + * @param {Function} predicate - A function to test each item emitted from the source Observable. + * @return {Observable} An Observable that begins emitting items emitted by the source Observable when the + * specified predicate becomes false. + * @method skipWhile + * @owner Observable */ -var SkipUntilSubscriber = (function (_super) { - __extends(SkipUntilSubscriber, _super); - function SkipUntilSubscriber(destination, notifier) { - _super.call(this, destination); - this.hasValue = false; - this.isInnerStopped = false; - this.add(subscribeToResult_1.subscribeToResult(this, notifier)); - } - SkipUntilSubscriber.prototype._next = function (value) { - if (this.hasValue) { - _super.prototype._next.call(this, value); - } - }; - SkipUntilSubscriber.prototype._complete = function () { - if (this.isInnerStopped) { - _super.prototype._complete.call(this); - } - else { - this.unsubscribe(); - } - }; - SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.hasValue = true; - }; - SkipUntilSubscriber.prototype.notifyComplete = function () { - this.isInnerStopped = true; - if (this.isStopped) { - _super.prototype._complete.call(this); - } - }; - return SkipUntilSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); +function skipWhile(predicate) { + return skipWhile_1.skipWhile(predicate)(this); +} +exports.skipWhile = skipWhile; -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],127:[function(require,module,exports){ +},{"../operators/skipWhile":196}],150:[function(require,module,exports){ "use strict"; -var ArrayObservable_1 = require('../observable/ArrayObservable'); -var ScalarObservable_1 = require('../observable/ScalarObservable'); -var EmptyObservable_1 = require('../observable/EmptyObservable'); -var concat_1 = require('./concat'); -var isScheduler_1 = require('../util/isScheduler'); +var startWith_1 = require('../operators/startWith'); +/* tslint:enable:max-line-length */ /** - * Returns an Observable that emits the items in a specified Iterable before it begins to emit items emitted by the - * source Observable. + * Returns an Observable that emits the items you specify as arguments before it begins to emit + * items emitted by the source Observable. * * * - * @param {Values} an Iterable that contains the items you want the modified Observable to emit first. - * @return {Observable} an Observable that emits the items in the specified Iterable and then emits the items + * @param {...T} values - Items you want the modified Observable to emit first. + * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling + * the emissions of the `next` notifications. + * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items * emitted by the source Observable. * @method startWith * @owner Observable @@ -10300,35 +10292,14 @@ function startWith() { for (var _i = 0; _i < arguments.length; _i++) { array[_i - 0] = arguments[_i]; } - var scheduler = array[array.length - 1]; - if (isScheduler_1.isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - var len = array.length; - if (len === 1) { - return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this); - } - else if (len > 1) { - return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this); - } - else { - return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this); - } + return startWith_1.startWith.apply(void 0, array)(this); } exports.startWith = startWith; -},{"../observable/ArrayObservable":79,"../observable/EmptyObservable":82,"../observable/ScalarObservable":89,"../util/isScheduler":152,"./concat":103}],128:[function(require,module,exports){ +},{"../operators/startWith":197}],151:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var switchMap_1 = require('../operators/switchMap'); +/* tslint:enable:max-line-length */ /** * Projects each source value to an Observable which is merged in the output * Observable, emitting values only from the most recently projected Observable. @@ -10358,7 +10329,7 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); * @see {@link switch} * @see {@link switchMapTo} * - * @param {function(value: T, ?index: number): Observable} project A function + * @param {function(value: T, ?index: number): ObservableInput} project A function * that, when applied to an item emitted by the source Observable, returns an * Observable. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector] @@ -10377,99 +10348,13 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); * @owner Observable */ function switchMap(project, resultSelector) { - return this.lift(new SwitchMapOperator(project, resultSelector)); + return switchMap_1.switchMap(project, resultSelector)(this); } exports.switchMap = switchMap; -var SwitchMapOperator = (function () { - function SwitchMapOperator(project, resultSelector) { - this.project = project; - this.resultSelector = resultSelector; - } - SwitchMapOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector)); - }; - return SwitchMapOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var SwitchMapSubscriber = (function (_super) { - __extends(SwitchMapSubscriber, _super); - function SwitchMapSubscriber(destination, project, resultSelector) { - _super.call(this, destination); - this.project = project; - this.resultSelector = resultSelector; - this.index = 0; - } - SwitchMapSubscriber.prototype._next = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (error) { - this.destination.error(error); - return; - } - this._innerSub(result, value, index); - }; - SwitchMapSubscriber.prototype._innerSub = function (result, value, index) { - var innerSubscription = this.innerSubscription; - if (innerSubscription) { - innerSubscription.unsubscribe(); - } - this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index)); - }; - SwitchMapSubscriber.prototype._complete = function () { - var innerSubscription = this.innerSubscription; - if (!innerSubscription || innerSubscription.closed) { - _super.prototype._complete.call(this); - } - }; - SwitchMapSubscriber.prototype._unsubscribe = function () { - this.innerSubscription = null; - }; - SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) { - this.remove(innerSub); - this.innerSubscription = null; - if (this.isStopped) { - _super.prototype._complete.call(this); - } - }; - SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - if (this.resultSelector) { - this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex); - } - else { - this.destination.next(innerValue); - } - }; - SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) { - var result; - try { - result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return SwitchMapSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],129:[function(require,module,exports){ +},{"../operators/switchMap":198}],152:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Subscriber_1 = require('../Subscriber'); -var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError'); -var EmptyObservable_1 = require('../observable/EmptyObservable'); +var take_1 = require('../operators/take'); /** * Emits only the first `count` values emitted by the source Observable. * @@ -10504,60 +10389,13 @@ var EmptyObservable_1 = require('../observable/EmptyObservable'); * @owner Observable */ function take(count) { - if (count === 0) { - return new EmptyObservable_1.EmptyObservable(); - } - else { - return this.lift(new TakeOperator(count)); - } + return take_1.take(count)(this); } exports.take = take; -var TakeOperator = (function () { - function TakeOperator(total) { - this.total = total; - if (this.total < 0) { - throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; - } - } - TakeOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new TakeSubscriber(subscriber, this.total)); - }; - return TakeOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var TakeSubscriber = (function (_super) { - __extends(TakeSubscriber, _super); - function TakeSubscriber(destination, total) { - _super.call(this, destination); - this.total = total; - this.count = 0; - } - TakeSubscriber.prototype._next = function (value) { - var total = this.total; - if (++this.count <= total) { - this.destination.next(value); - if (this.count === total) { - this.destination.complete(); - this.unsubscribe(); - } - } - }; - return TakeSubscriber; -}(Subscriber_1.Subscriber)); - -},{"../Subscriber":35,"../observable/EmptyObservable":82,"../util/ArgumentOutOfRangeError":143}],130:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); + +},{"../operators/take":199}],153:[function(require,module,exports){ +"use strict"; +var takeUntil_1 = require('../operators/takeUntil'); /** * Emits the values emitted by the source Observable until a `notifier` * Observable emits a value. @@ -10569,8 +10407,8 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); * * `takeUntil` subscribes and begins mirroring the source Observable. It also * monitors a second Observable, `notifier` that you provide. If the `notifier` - * emits a value or a complete notification, the output Observable stops - * mirroring the source Observable and completes. + * emits a value, the output Observable stops mirroring the source Observable + * and completes. * * @example Tick every second until the first click happens * var interval = Rx.Observable.interval(1000); @@ -10592,48 +10430,133 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); * @owner Observable */ function takeUntil(notifier) { - return this.lift(new TakeUntilOperator(notifier)); + return takeUntil_1.takeUntil(notifier)(this); } exports.takeUntil = takeUntil; -var TakeUntilOperator = (function () { - function TakeUntilOperator(notifier) { - this.notifier = notifier; - } - TakeUntilOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new TakeUntilSubscriber(subscriber, this.notifier)); - }; - return TakeUntilOperator; -}()); + +},{"../operators/takeUntil":201}],154:[function(require,module,exports){ +"use strict"; +var takeWhile_1 = require('../operators/takeWhile'); /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} + * Emits values emitted by the source Observable so long as each value satisfies + * the given `predicate`, and then completes as soon as this `predicate` is not + * satisfied. + * + * Takes values from the source only while they pass the + * condition given. When the first value does not satisfy, it completes. + * + * + * + * `takeWhile` subscribes and begins mirroring the source Observable. Each value + * emitted on the source is given to the `predicate` function which returns a + * boolean, representing a condition to be satisfied by the source values. The + * output Observable emits the source values until such time as the `predicate` + * returns false, at which point `takeWhile` stops mirroring the source + * Observable and completes the output Observable. + * + * @example Emit click events only while the clientX property is greater than 200 + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.takeWhile(ev => ev.clientX > 200); + * result.subscribe(x => console.log(x)); + * + * @see {@link take} + * @see {@link takeLast} + * @see {@link takeUntil} + * @see {@link skip} + * + * @param {function(value: T, index: number): boolean} predicate A function that + * evaluates a value emitted by the source Observable and returns a boolean. + * Also takes the (zero-based) index as the second argument. + * @return {Observable} An Observable that emits the values from the source + * Observable so long as each value satisfies the condition defined by the + * `predicate`, then completes. + * @method takeWhile + * @owner Observable */ -var TakeUntilSubscriber = (function (_super) { - __extends(TakeUntilSubscriber, _super); - function TakeUntilSubscriber(destination, notifier) { - _super.call(this, destination); - this.notifier = notifier; - this.add(subscribeToResult_1.subscribeToResult(this, notifier)); - } - TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.complete(); - }; - TakeUntilSubscriber.prototype.notifyComplete = function () { - // noop - }; - return TakeUntilSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); +function takeWhile(predicate) { + return takeWhile_1.takeWhile(predicate)(this); +} +exports.takeWhile = takeWhile; -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],131:[function(require,module,exports){ +},{"../operators/takeWhile":202}],155:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); +var async_1 = require('../scheduler/async'); +var timeout_1 = require('../operators/timeout'); +/** + * + * Errors if Observable does not emit a value in given time span. + * + * Timeouts on Observable that doesn't emit values fast enough. + * + * + * + * `timeout` operator accepts as an argument either a number or a Date. + * + * If number was provided, it returns an Observable that behaves like a source + * Observable, unless there is a period of time where there is no value emitted. + * So if you provide `100` as argument and first value comes after 50ms from + * the moment of subscription, this value will be simply re-emitted by the resulting + * Observable. If however after that 100ms passes without a second value being emitted, + * stream will end with an error and source Observable will be unsubscribed. + * These checks are performed throughout whole lifecycle of Observable - from the moment + * it was subscribed to, until it completes or errors itself. Thus every value must be + * emitted within specified period since previous value. + * + * If provided argument was Date, returned Observable behaves differently. It throws + * if Observable did not complete before provided Date. This means that periods between + * emission of particular values do not matter in this case. If Observable did not complete + * before provided Date, source Observable will be unsubscribed. Other than that, resulting + * stream behaves just as source Observable. + * + * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments) + * when returned Observable will check if source stream emitted value or completed. + * + * @example Check if ticks are emitted within certain timespan + * const seconds = Rx.Observable.interval(1000); + * + * seconds.timeout(1100) // Let's use bigger timespan to be safe, + * // since `interval` might fire a bit later then scheduled. + * .subscribe( + * value => console.log(value), // Will emit numbers just as regular `interval` would. + * err => console.log(err) // Will never be called. + * ); + * + * seconds.timeout(900).subscribe( + * value => console.log(value), // Will never be called. + * err => console.log(err) // Will emit error before even first value is emitted, + * // since it did not arrive within 900ms period. + * ); + * + * @example Use Date to check if Observable completed + * const seconds = Rx.Observable.interval(1000); + * + * seconds.timeout(new Date("December 17, 2020 03:24:00")) + * .subscribe( + * value => console.log(value), // Will emit values as regular `interval` would + * // until December 17, 2020 at 03:24:00. + * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error, + * // since Observable did not complete by then. + * ); + * + * @see {@link timeoutWith} + * + * @param {number|Date} due Number specifying period within which Observable must emit values + * or Date specifying before when Observable should complete + * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur. + * @return {Observable} Observable that mirrors behaviour of source, unless timeout checks fail. + * @method timeout + * @owner Observable + */ +function timeout(due, scheduler) { + if (scheduler === void 0) { scheduler = async_1.async; } + return timeout_1.timeout(due, scheduler)(this); +} +exports.timeout = timeout; + +},{"../operators/timeout":204,"../scheduler/async":212}],156:[function(require,module,exports){ +"use strict"; +var withLatestFrom_1 = require('../operators/withLatestFrom'); +/* tslint:enable:max-line-length */ /** * Combines the source Observable with other Observables to create an Observable * whose values are calculated from the latest values of each, only when the @@ -10659,7 +10582,7 @@ var subscribeToResult_1 = require('../util/subscribeToResult'); * * @see {@link combineLatest} * - * @param {Observable} other An input Observable to combine with the source + * @param {ObservableInput} other An input Observable to combine with the source * Observable. More than one input Observables may be given as argument. * @param {Function} [project] Projection function for combining values * together. Receives all values in order of the Observables passed, where the @@ -10677,98 +10600,14 @@ function withLatestFrom() { for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } - var project; - if (typeof args[args.length - 1] === 'function') { - project = args.pop(); - } - var observables = args; - return this.lift(new WithLatestFromOperator(observables, project)); + return withLatestFrom_1.withLatestFrom.apply(void 0, args)(this); } exports.withLatestFrom = withLatestFrom; -/* tslint:enable:max-line-length */ -var WithLatestFromOperator = (function () { - function WithLatestFromOperator(observables, project) { - this.observables = observables; - this.project = project; - } - WithLatestFromOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project)); - }; - return WithLatestFromOperator; -}()); -/** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ -var WithLatestFromSubscriber = (function (_super) { - __extends(WithLatestFromSubscriber, _super); - function WithLatestFromSubscriber(destination, observables, project) { - _super.call(this, destination); - this.observables = observables; - this.project = project; - this.toRespond = []; - var len = observables.length; - this.values = new Array(len); - for (var i = 0; i < len; i++) { - this.toRespond.push(i); - } - for (var i = 0; i < len; i++) { - var observable = observables[i]; - this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i)); - } - } - WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values[outerIndex] = innerValue; - var toRespond = this.toRespond; - if (toRespond.length > 0) { - var found = toRespond.indexOf(outerIndex); - if (found !== -1) { - toRespond.splice(found, 1); - } - } - }; - WithLatestFromSubscriber.prototype.notifyComplete = function () { - // noop - }; - WithLatestFromSubscriber.prototype._next = function (value) { - if (this.toRespond.length === 0) { - var args = [value].concat(this.values); - if (this.project) { - this._tryProject(args); - } - else { - this.destination.next(args); - } - } - }; - WithLatestFromSubscriber.prototype._tryProject = function (args) { - var result; - try { - result = this.project.apply(this, args); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return WithLatestFromSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); -},{"../OuterSubscriber":30,"../util/subscribeToResult":154}],132:[function(require,module,exports){ +},{"../operators/withLatestFrom":205}],157:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var ArrayObservable_1 = require('../observable/ArrayObservable'); -var isArray_1 = require('../util/isArray'); -var Subscriber_1 = require('../Subscriber'); -var OuterSubscriber_1 = require('../OuterSubscriber'); -var subscribeToResult_1 = require('../util/subscribeToResult'); -var iterator_1 = require('../symbol/iterator'); +var zip_1 = require('../operators/zip'); +/* tslint:enable:max-line-length */ /** * @param observables * @return {Observable} @@ -10780,2169 +10619,7173 @@ function zipProto() { for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } - observables.unshift(this); - return zipStatic.apply(this, observables); + return zip_1.zip.apply(void 0, observables)(this); } exports.zipProto = zipProto; -/* tslint:enable:max-line-length */ + +},{"../operators/zip":206}],158:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var tryCatch_1 = require('../util/tryCatch'); +var errorObject_1 = require('../util/errorObject'); +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); /** - * @param observables - * @return {Observable} - * @static true - * @name zip + * Ignores source values for a duration determined by another Observable, then + * emits the most recent value from the source Observable, then repeats this + * process. + * + * It's like {@link auditTime}, but the silencing + * duration is determined by a second Observable. + * + * + * + * `audit` is similar to `throttle`, but emits the last value from the silenced + * time window, instead of the first value. `audit` emits the most recent value + * from the source Observable on the output Observable as soon as its internal + * timer becomes disabled, and ignores source values while the timer is enabled. + * Initially, the timer is disabled. As soon as the first source value arrives, + * the timer is enabled by calling the `durationSelector` function with the + * source value, which returns the "duration" Observable. When the duration + * Observable emits a value or completes, the timer is disabled, then the most + * recent source value is emitted on the output Observable, and this process + * repeats for the next source value. + * + * @example Emit clicks at a rate of at most one click per second + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.audit(ev => Rx.Observable.interval(1000)); + * result.subscribe(x => console.log(x)); + * + * @see {@link auditTime} + * @see {@link debounce} + * @see {@link delayWhen} + * @see {@link sample} + * @see {@link throttle} + * + * @param {function(value: T): SubscribableOrPromise} durationSelector A function + * that receives a value from the source Observable, for computing the silencing + * duration, returned as an Observable or a Promise. + * @return {Observable} An Observable that performs rate-limiting of + * emissions from the source Observable. + * @method audit * @owner Observable */ -function zipStatic() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i - 0] = arguments[_i]; - } - var project = observables[observables.length - 1]; - if (typeof project === 'function') { - observables.pop(); - } - return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project)); +function audit(durationSelector) { + return function auditOperatorFunction(source) { + return source.lift(new AuditOperator(durationSelector)); + }; } -exports.zipStatic = zipStatic; -var ZipOperator = (function () { - function ZipOperator(project) { - this.project = project; +exports.audit = audit; +var AuditOperator = (function () { + function AuditOperator(durationSelector) { + this.durationSelector = durationSelector; } - ZipOperator.prototype.call = function (subscriber, source) { - return source._subscribe(new ZipSubscriber(subscriber, this.project)); + AuditOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector)); }; - return ZipOperator; + return AuditOperator; }()); -exports.ZipOperator = ZipOperator; /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ -var ZipSubscriber = (function (_super) { - __extends(ZipSubscriber, _super); - function ZipSubscriber(destination, project, values) { - if (values === void 0) { values = Object.create(null); } +var AuditSubscriber = (function (_super) { + __extends(AuditSubscriber, _super); + function AuditSubscriber(destination, durationSelector) { _super.call(this, destination); - this.index = 0; - this.iterators = []; - this.active = 0; - this.project = (typeof project === 'function') ? project : null; - this.values = values; + this.durationSelector = durationSelector; + this.hasValue = false; } - ZipSubscriber.prototype._next = function (value) { - var iterators = this.iterators; - var index = this.index++; - if (isArray_1.isArray(value)) { - iterators.push(new StaticArrayIterator(value)); + AuditSubscriber.prototype._next = function (value) { + this.value = value; + this.hasValue = true; + if (!this.throttled) { + var duration = tryCatch_1.tryCatch(this.durationSelector)(value); + if (duration === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } + else { + var innerSubscription = subscribeToResult_1.subscribeToResult(this, duration); + if (innerSubscription.closed) { + this.clearThrottle(); + } + else { + this.add(this.throttled = innerSubscription); + } + } } - else if (typeof value[iterator_1.$$iterator] === 'function') { - iterators.push(new StaticIterator(value[iterator_1.$$iterator]())); + }; + AuditSubscriber.prototype.clearThrottle = function () { + var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled; + if (throttled) { + this.remove(throttled); + this.throttled = null; + throttled.unsubscribe(); } - else { - iterators.push(new ZipBufferIterator(this.destination, this, value, index)); + if (hasValue) { + this.value = null; + this.hasValue = false; + this.destination.next(value); } }; - ZipSubscriber.prototype._complete = function () { - var iterators = this.iterators; - var len = iterators.length; - this.active = len; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - if (iterator.stillUnsubscribed) { - this.add(iterator.subscribe(iterator, i)); - } - else { - this.active--; // not an observable - } - } - }; - ZipSubscriber.prototype.notifyInactive = function () { - this.active--; - if (this.active === 0) { - this.destination.complete(); - } - }; - ZipSubscriber.prototype.checkIterators = function () { - var iterators = this.iterators; - var len = iterators.length; - var destination = this.destination; - // abort if not all of them have values - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { - return; - } - } - var shouldComplete = false; - var args = []; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - var result = iterator.next(); - // check to see if it's completed now that you've gotten - // the next value. - if (iterator.hasCompleted()) { - shouldComplete = true; - } - if (result.done) { - destination.complete(); - return; - } - args.push(result.value); - } - if (this.project) { - this._tryProject(args); - } - else { - destination.next(args); - } - if (shouldComplete) { - destination.complete(); - } - }; - ZipSubscriber.prototype._tryProject = function (args) { - var result; - try { - result = this.project.apply(this, args); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); + AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) { + this.clearThrottle(); }; - return ZipSubscriber; -}(Subscriber_1.Subscriber)); -exports.ZipSubscriber = ZipSubscriber; -var StaticIterator = (function () { - function StaticIterator(iterator) { - this.iterator = iterator; - this.nextResult = iterator.next(); - } - StaticIterator.prototype.hasValue = function () { - return true; - }; - StaticIterator.prototype.next = function () { - var result = this.nextResult; - this.nextResult = this.iterator.next(); - return result; + AuditSubscriber.prototype.notifyComplete = function () { + this.clearThrottle(); }; - StaticIterator.prototype.hasCompleted = function () { - var nextResult = this.nextResult; - return nextResult && nextResult.done; + return AuditSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); + +},{"../OuterSubscriber":31,"../util/errorObject":224,"../util/subscribeToResult":237,"../util/tryCatch":239}],159:[function(require,module,exports){ +"use strict"; +var async_1 = require('../scheduler/async'); +var audit_1 = require('./audit'); +var timer_1 = require('../observable/timer'); +/** + * Ignores source values for `duration` milliseconds, then emits the most recent + * value from the source Observable, then repeats this process. + * + * When it sees a source values, it ignores that plus + * the next ones for `duration` milliseconds, and then it emits the most recent + * value from the source. + * + * + * + * `auditTime` is similar to `throttleTime`, but emits the last value from the + * silenced time window, instead of the first value. `auditTime` emits the most + * recent value from the source Observable on the output Observable as soon as + * its internal timer becomes disabled, and ignores source values while the + * timer is enabled. Initially, the timer is disabled. As soon as the first + * source value arrives, the timer is enabled. After `duration` milliseconds (or + * the time unit determined internally by the optional `scheduler`) has passed, + * the timer is disabled, then the most recent source value is emitted on the + * output Observable, and this process repeats for the next source value. + * Optionally takes a {@link IScheduler} for managing timers. + * + * @example Emit clicks at a rate of at most one click per second + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.auditTime(1000); + * result.subscribe(x => console.log(x)); + * + * @see {@link audit} + * @see {@link debounceTime} + * @see {@link delay} + * @see {@link sampleTime} + * @see {@link throttleTime} + * + * @param {number} duration Time to wait before emitting the most recent source + * value, measured in milliseconds or the time unit determined internally + * by the optional `scheduler`. + * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for + * managing the timers that handle the rate-limiting behavior. + * @return {Observable} An Observable that performs rate-limiting of + * emissions from the source Observable. + * @method auditTime + * @owner Observable + */ +function auditTime(duration, scheduler) { + if (scheduler === void 0) { scheduler = async_1.async; } + return audit_1.audit(function () { return timer_1.timer(duration, scheduler); }); +} +exports.auditTime = auditTime; + +},{"../observable/timer":114,"../scheduler/async":212,"./audit":158}],160:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/** + * Buffers the source Observable values until `closingNotifier` emits. + * + * Collects values from the past as an array, and emits + * that array only when another Observable emits. + * + * + * + * Buffers the incoming Observable values until the given `closingNotifier` + * Observable emits a value, at which point it emits the buffer on the output + * Observable and starts a new buffer internally, awaiting the next time + * `closingNotifier` emits. + * + * @example On every click, emit array of most recent interval events + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var interval = Rx.Observable.interval(1000); + * var buffered = interval.buffer(clicks); + * buffered.subscribe(x => console.log(x)); + * + * @see {@link bufferCount} + * @see {@link bufferTime} + * @see {@link bufferToggle} + * @see {@link bufferWhen} + * @see {@link window} + * + * @param {Observable} closingNotifier An Observable that signals the + * buffer to be emitted on the output Observable. + * @return {Observable} An Observable of buffers, which are arrays of + * values. + * @method buffer + * @owner Observable + */ +function buffer(closingNotifier) { + return function bufferOperatorFunction(source) { + return source.lift(new BufferOperator(closingNotifier)); }; - return StaticIterator; -}()); -var StaticArrayIterator = (function () { - function StaticArrayIterator(array) { - this.array = array; - this.index = 0; - this.length = 0; - this.length = array.length; +} +exports.buffer = buffer; +var BufferOperator = (function () { + function BufferOperator(closingNotifier) { + this.closingNotifier = closingNotifier; } - StaticArrayIterator.prototype[iterator_1.$$iterator] = function () { - return this; - }; - StaticArrayIterator.prototype.next = function (value) { - var i = this.index++; - var array = this.array; - return i < this.length ? { value: array[i], done: false } : { value: null, done: true }; - }; - StaticArrayIterator.prototype.hasValue = function () { - return this.array.length > this.index; - }; - StaticArrayIterator.prototype.hasCompleted = function () { - return this.array.length === this.index; + BufferOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier)); }; - return StaticArrayIterator; + return BufferOperator; }()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ -var ZipBufferIterator = (function (_super) { - __extends(ZipBufferIterator, _super); - function ZipBufferIterator(destination, parent, observable, index) { +var BufferSubscriber = (function (_super) { + __extends(BufferSubscriber, _super); + function BufferSubscriber(destination, closingNotifier) { _super.call(this, destination); - this.parent = parent; - this.observable = observable; - this.index = index; - this.stillUnsubscribed = true; this.buffer = []; - this.isComplete = false; + this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier)); } - ZipBufferIterator.prototype[iterator_1.$$iterator] = function () { - return this; + BufferSubscriber.prototype._next = function (value) { + this.buffer.push(value); }; - // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next - // this is legit because `next()` will never be called by a subscription in this case. - ZipBufferIterator.prototype.next = function () { + BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { var buffer = this.buffer; - if (buffer.length === 0 && this.isComplete) { - return { value: null, done: true }; - } - else { - return { value: buffer.shift(), done: false }; - } - }; - ZipBufferIterator.prototype.hasValue = function () { - return this.buffer.length > 0; - }; - ZipBufferIterator.prototype.hasCompleted = function () { - return this.buffer.length === 0 && this.isComplete; - }; - ZipBufferIterator.prototype.notifyComplete = function () { - if (this.buffer.length > 0) { - this.isComplete = true; - this.parent.notifyInactive(); - } - else { - this.destination.complete(); - } - }; - ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.buffer.push(innerValue); - this.parent.checkIterators(); - }; - ZipBufferIterator.prototype.subscribe = function (value, index) { - return subscribeToResult_1.subscribeToResult(this, this.observable, this, index); + this.buffer = []; + this.destination.next(buffer); }; - return ZipBufferIterator; + return BufferSubscriber; }(OuterSubscriber_1.OuterSubscriber)); -},{"../OuterSubscriber":30,"../Subscriber":35,"../observable/ArrayObservable":79,"../symbol/iterator":140,"../util/isArray":148,"../util/subscribeToResult":154}],133:[function(require,module,exports){ +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],161:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; -var Subscription_1 = require('../Subscription'); +var Subscriber_1 = require('../Subscriber'); /** - * A unit of work to be executed in a {@link Scheduler}. An action is typically - * created from within a Scheduler and an RxJS user does not need to concern - * themselves about creating and manipulating an Action. + * Buffers the source Observable values until the size hits the maximum + * `bufferSize` given. * - * ```ts - * class Action extends Subscription { - * new (scheduler: Scheduler, work: (state?: T) => void); - * schedule(state?: T, delay: number = 0): Subscription; - * } - * ``` + * Collects values from the past as an array, and emits + * that array only when its size reaches `bufferSize`. * - * @class Action + * + * + * Buffers a number of values from the source Observable by `bufferSize` then + * emits the buffer and clears it, and starts a new buffer each + * `startBufferEvery` values. If `startBufferEvery` is not provided or is + * `null`, then new buffers are started immediately at the start of the source + * and when each buffer closes and is emitted. + * + * @example Emit the last two click events as an array + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var buffered = clicks.bufferCount(2); + * buffered.subscribe(x => console.log(x)); + * + * @example On every click, emit the last two click events as an array + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var buffered = clicks.bufferCount(2, 1); + * buffered.subscribe(x => console.log(x)); + * + * @see {@link buffer} + * @see {@link bufferTime} + * @see {@link bufferToggle} + * @see {@link bufferWhen} + * @see {@link pairwise} + * @see {@link windowCount} + * + * @param {number} bufferSize The maximum size of the buffer emitted. + * @param {number} [startBufferEvery] Interval at which to start a new buffer. + * For example if `startBufferEvery` is `2`, then a new buffer will be started + * on every other value from the source. A new buffer is started at the + * beginning of the source by default. + * @return {Observable} An Observable of arrays of buffered values. + * @method bufferCount + * @owner Observable */ -var Action = (function (_super) { - __extends(Action, _super); - function Action(scheduler, work) { - _super.call(this); - } - /** - * Schedules this action on its parent Scheduler for execution. May be passed - * some context object, `state`. May happen at some point in the future, - * according to the `delay` parameter, if specified. - * @param {T} [state] Some contextual data that the `work` function uses when - * called by the Scheduler. - * @param {number} [delay] Time to wait before executing the work, where the - * time unit is implicit and defined by the Scheduler. - * @return {void} - */ - Action.prototype.schedule = function (state, delay) { - if (delay === void 0) { delay = 0; } - return this; +function bufferCount(bufferSize, startBufferEvery) { + if (startBufferEvery === void 0) { startBufferEvery = null; } + return function bufferCountOperatorFunction(source) { + return source.lift(new BufferCountOperator(bufferSize, startBufferEvery)); }; - return Action; -}(Subscription_1.Subscription)); -exports.Action = Action; - -},{"../Subscription":36}],134:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var root_1 = require('../util/root'); -var Action_1 = require('./Action'); +} +exports.bufferCount = bufferCount; +var BufferCountOperator = (function () { + function BufferCountOperator(bufferSize, startBufferEvery) { + this.bufferSize = bufferSize; + this.startBufferEvery = startBufferEvery; + if (!startBufferEvery || bufferSize === startBufferEvery) { + this.subscriberClass = BufferCountSubscriber; + } + else { + this.subscriberClass = BufferSkipCountSubscriber; + } + } + BufferCountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery)); + }; + return BufferCountOperator; +}()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ -var AsyncAction = (function (_super) { - __extends(AsyncAction, _super); - function AsyncAction(scheduler, work) { - _super.call(this, scheduler, work); - this.scheduler = scheduler; - this.work = work; - this.pending = false; +var BufferCountSubscriber = (function (_super) { + __extends(BufferCountSubscriber, _super); + function BufferCountSubscriber(destination, bufferSize) { + _super.call(this, destination); + this.bufferSize = bufferSize; + this.buffer = []; } - AsyncAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { delay = 0; } - if (this.closed) { - return this; - } - // Always replace the current state with the new state. - this.state = state; - // Set the pending flag indicating that this action has been scheduled, or - // has recursively rescheduled itself. - this.pending = true; - var id = this.id; - var scheduler = this.scheduler; - // - // Important implementation note: - // - // Actions only execute once by default, unless rescheduled from within the - // scheduled callback. This allows us to implement single and repeat - // actions via the same code path, without adding API surface area, as well - // as mimic traditional recursion but across asynchronous boundaries. - // - // However, JS runtimes and timers distinguish between intervals achieved by - // serial `setTimeout` calls vs. a single `setInterval` call. An interval of - // serial `setTimeout` calls can be individually delayed, which delays - // scheduling the next `setTimeout`, and so on. `setInterval` attempts to - // guarantee the interval callback will be invoked more precisely to the - // interval period, regardless of load. - // - // Therefore, we use `setInterval` to schedule single and repeat actions. - // If the action reschedules itself with the same delay, the interval is not - // canceled. If the action doesn't reschedule, or reschedules with a - // different delay, the interval will be canceled after scheduled callback - // execution. - // - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.delay = delay; - // If this action has already an async Id, don't request a new one. - this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { delay = 0; } - return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { delay = 0; } - // If this action is rescheduled with the same delay time, don't clear the interval id. - if (delay !== null && this.delay === delay) { - return id; + BufferCountSubscriber.prototype._next = function (value) { + var buffer = this.buffer; + buffer.push(value); + if (buffer.length == this.bufferSize) { + this.destination.next(buffer); + this.buffer = []; } - // Otherwise, if the action's delay time is different from the current delay, - // clear the interval id - return root_1.root.clearInterval(id) && undefined || undefined; }; - /** - * Immediately executes this action and the `work` it contains. - * @return {any} - */ - AsyncAction.prototype.execute = function (state, delay) { - if (this.closed) { - return new Error('executing a cancelled action'); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } - else if (this.pending === false && this.id != null) { - // Dequeue if the action didn't reschedule itself. Don't call - // unsubscribe(), because the action could reschedule later. - // For example: - // ``` - // scheduler.schedule(function doWork(counter) { - // /* ... I'm a busy worker bee ... */ - // var originalAction = this; - // /* wait 100ms before rescheduling the action */ - // setTimeout(function () { - // originalAction.schedule(counter + 1); - // }, 100); - // }, 1000); - // ``` - this.id = this.recycleAsyncId(this.scheduler, this.id, null); + BufferCountSubscriber.prototype._complete = function () { + var buffer = this.buffer; + if (buffer.length > 0) { + this.destination.next(buffer); } + _super.prototype._complete.call(this); }; - AsyncAction.prototype._execute = function (state, delay) { - var errored = false; - var errorValue = undefined; - try { - this.work(state); - } - catch (e) { - errored = true; - errorValue = !!e && e || new Error(e); + return BufferCountSubscriber; +}(Subscriber_1.Subscriber)); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var BufferSkipCountSubscriber = (function (_super) { + __extends(BufferSkipCountSubscriber, _super); + function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) { + _super.call(this, destination); + this.bufferSize = bufferSize; + this.startBufferEvery = startBufferEvery; + this.buffers = []; + this.count = 0; + } + BufferSkipCountSubscriber.prototype._next = function (value) { + var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count; + this.count++; + if (count % startBufferEvery === 0) { + buffers.push([]); } - if (errored) { - this.unsubscribe(); - return errorValue; + for (var i = buffers.length; i--;) { + var buffer = buffers[i]; + buffer.push(value); + if (buffer.length === bufferSize) { + buffers.splice(i, 1); + this.destination.next(buffer); + } } }; - AsyncAction.prototype._unsubscribe = function () { - var id = this.id; - var scheduler = this.scheduler; - var actions = scheduler.actions; - var index = actions.indexOf(this); - this.work = null; - this.delay = null; - this.state = null; - this.pending = false; - this.scheduler = null; - if (index !== -1) { - actions.splice(index, 1); - } - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); + BufferSkipCountSubscriber.prototype._complete = function () { + var _a = this, buffers = _a.buffers, destination = _a.destination; + while (buffers.length > 0) { + var buffer = buffers.shift(); + if (buffer.length > 0) { + destination.next(buffer); + } } + _super.prototype._complete.call(this); }; - return AsyncAction; -}(Action_1.Action)); -exports.AsyncAction = AsyncAction; + return BufferSkipCountSubscriber; +}(Subscriber_1.Subscriber)); -},{"../util/root":153,"./Action":133}],135:[function(require,module,exports){ +},{"../Subscriber":36}],162:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; -var Scheduler_1 = require('../Scheduler'); -var AsyncScheduler = (function (_super) { - __extends(AsyncScheduler, _super); - function AsyncScheduler() { - _super.apply(this, arguments); - this.actions = []; - /** - * A flag to indicate whether the Scheduler is currently executing a batch of - * queued actions. - * @type {boolean} - */ - this.active = false; - /** - * An internal ID used to track the latest asynchronous task such as those - * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and - * others. - * @type {any} - */ - this.scheduled = undefined; +var Subscription_1 = require('../Subscription'); +var tryCatch_1 = require('../util/tryCatch'); +var errorObject_1 = require('../util/errorObject'); +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/** + * Buffers the source Observable values, using a factory function of closing + * Observables to determine when to close, emit, and reset the buffer. + * + * Collects values from the past as an array. When it + * starts collecting values, it calls a function that returns an Observable that + * tells when to close the buffer and restart collecting. + * + * + * + * Opens a buffer immediately, then closes the buffer when the observable + * returned by calling `closingSelector` function emits a value. When it closes + * the buffer, it immediately opens a new buffer and repeats the process. + * + * @example Emit an array of the last clicks every [1-5] random seconds + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var buffered = clicks.bufferWhen(() => + * Rx.Observable.interval(1000 + Math.random() * 4000) + * ); + * buffered.subscribe(x => console.log(x)); + * + * @see {@link buffer} + * @see {@link bufferCount} + * @see {@link bufferTime} + * @see {@link bufferToggle} + * @see {@link windowWhen} + * + * @param {function(): Observable} closingSelector A function that takes no + * arguments and returns an Observable that signals buffer closure. + * @return {Observable} An observable of arrays of buffered values. + * @method bufferWhen + * @owner Observable + */ +function bufferWhen(closingSelector) { + return function (source) { + return source.lift(new BufferWhenOperator(closingSelector)); + }; +} +exports.bufferWhen = bufferWhen; +var BufferWhenOperator = (function () { + function BufferWhenOperator(closingSelector) { + this.closingSelector = closingSelector; } - AsyncScheduler.prototype.flush = function (action) { - var actions = this.actions; - if (this.active) { - actions.push(action); - return; + BufferWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector)); + }; + return BufferWhenOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var BufferWhenSubscriber = (function (_super) { + __extends(BufferWhenSubscriber, _super); + function BufferWhenSubscriber(destination, closingSelector) { + _super.call(this, destination); + this.closingSelector = closingSelector; + this.subscribing = false; + this.openBuffer(); + } + BufferWhenSubscriber.prototype._next = function (value) { + this.buffer.push(value); + }; + BufferWhenSubscriber.prototype._complete = function () { + var buffer = this.buffer; + if (buffer) { + this.destination.next(buffer); } - var error; - this.active = true; - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (action = actions.shift()); // exhaust the scheduler queue - this.active = false; - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; + _super.prototype._complete.call(this); + }; + BufferWhenSubscriber.prototype._unsubscribe = function () { + this.buffer = null; + this.subscribing = false; + }; + BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.openBuffer(); + }; + BufferWhenSubscriber.prototype.notifyComplete = function () { + if (this.subscribing) { + this.complete(); + } + else { + this.openBuffer(); } }; - return AsyncScheduler; -}(Scheduler_1.Scheduler)); -exports.AsyncScheduler = AsyncScheduler; + BufferWhenSubscriber.prototype.openBuffer = function () { + var closingSubscription = this.closingSubscription; + if (closingSubscription) { + this.remove(closingSubscription); + closingSubscription.unsubscribe(); + } + var buffer = this.buffer; + if (this.buffer) { + this.destination.next(buffer); + } + this.buffer = []; + var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)(); + if (closingNotifier === errorObject_1.errorObject) { + this.error(errorObject_1.errorObject.e); + } + else { + closingSubscription = new Subscription_1.Subscription(); + this.closingSubscription = closingSubscription; + this.add(closingSubscription); + this.subscribing = true; + closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier)); + this.subscribing = false; + } + }; + return BufferWhenSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); -},{"../Scheduler":32}],136:[function(require,module,exports){ +},{"../OuterSubscriber":31,"../Subscription":37,"../util/errorObject":224,"../util/subscribeToResult":237,"../util/tryCatch":239}],163:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; -var AsyncAction_1 = require('./AsyncAction'); +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/** + * Catches errors on the observable to be handled by returning a new observable or throwing an error. + * + * + * + * @example Continues with a different Observable when there's an error + * + * Observable.of(1, 2, 3, 4, 5) + * .map(n => { + * if (n == 4) { + * throw 'four!'; + * } + * return n; + * }) + * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V')) + * .subscribe(x => console.log(x)); + * // 1, 2, 3, I, II, III, IV, V + * + * @example Retries the caught source Observable again in case of error, similar to retry() operator + * + * Observable.of(1, 2, 3, 4, 5) + * .map(n => { + * if (n === 4) { + * throw 'four!'; + * } + * return n; + * }) + * .catch((err, caught) => caught) + * .take(30) + * .subscribe(x => console.log(x)); + * // 1, 2, 3, 1, 2, 3, ... + * + * @example Throws a new error when the source Observable throws an error + * + * Observable.of(1, 2, 3, 4, 5) + * .map(n => { + * if (n == 4) { + * throw 'four!'; + * } + * return n; + * }) + * .catch(err => { + * throw 'error in source. Details: ' + err; + * }) + * .subscribe( + * x => console.log(x), + * err => console.log(err) + * ); + * // 1, 2, 3, error in source. Details: four! + * + * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which + * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable + * is returned by the `selector` will be used to continue the observable chain. + * @return {Observable} An observable that originates from either the source or the observable returned by the + * catch `selector` function. + * @name catchError + */ +function catchError(selector) { + return function catchErrorOperatorFunction(source) { + var operator = new CatchOperator(selector); + var caught = source.lift(operator); + return (operator.caught = caught); + }; +} +exports.catchError = catchError; +var CatchOperator = (function () { + function CatchOperator(selector) { + this.selector = selector; + } + CatchOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); + }; + return CatchOperator; +}()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ -var QueueAction = (function (_super) { - __extends(QueueAction, _super); - function QueueAction(scheduler, work) { - _super.call(this, scheduler, work); - this.scheduler = scheduler; - this.work = work; - } - QueueAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { delay = 0; } - if (delay > 0) { - return _super.prototype.schedule.call(this, state, delay); - } - this.delay = delay; - this.state = state; - this.scheduler.flush(this); - return this; - }; - QueueAction.prototype.execute = function (state, delay) { - return (delay > 0 || this.closed) ? - _super.prototype.execute.call(this, state, delay) : - this._execute(state, delay); - }; - QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { delay = 0; } - // If delay is greater than 0, enqueue as an async action. - if (delay !== null && delay > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); - } - // Otherwise flush the scheduler starting with this action. - return scheduler.flush(this); - }; - return QueueAction; -}(AsyncAction_1.AsyncAction)); -exports.QueueAction = QueueAction; - -},{"./AsyncAction":134}],137:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var AsyncScheduler_1 = require('./AsyncScheduler'); -var QueueScheduler = (function (_super) { - __extends(QueueScheduler, _super); - function QueueScheduler() { - _super.apply(this, arguments); +var CatchSubscriber = (function (_super) { + __extends(CatchSubscriber, _super); + function CatchSubscriber(destination, selector, caught) { + _super.call(this, destination); + this.selector = selector; + this.caught = caught; } - return QueueScheduler; -}(AsyncScheduler_1.AsyncScheduler)); -exports.QueueScheduler = QueueScheduler; - -},{"./AsyncScheduler":135}],138:[function(require,module,exports){ -"use strict"; -var AsyncAction_1 = require('./AsyncAction'); -var AsyncScheduler_1 = require('./AsyncScheduler'); -exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction); - -},{"./AsyncAction":134,"./AsyncScheduler":135}],139:[function(require,module,exports){ -"use strict"; -var QueueAction_1 = require('./QueueAction'); -var QueueScheduler_1 = require('./QueueScheduler'); -exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction); - -},{"./QueueAction":136,"./QueueScheduler":137}],140:[function(require,module,exports){ -"use strict"; -var root_1 = require('../util/root'); -var Symbol = root_1.root.Symbol; -if (typeof Symbol === 'function') { - if (Symbol.iterator) { - exports.$$iterator = Symbol.iterator; - } - else if (typeof Symbol.for === 'function') { - exports.$$iterator = Symbol.for('iterator'); - } -} -else { - if (root_1.root.Set && typeof new root_1.root.Set()['@@iterator'] === 'function') { - // Bug for mozilla version - exports.$$iterator = '@@iterator'; - } - else if (root_1.root.Map) { - // es6-shim specific logic - var keys = Object.getOwnPropertyNames(root_1.root.Map.prototype); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (key !== 'entries' && key !== 'size' && root_1.root.Map.prototype[key] === root_1.root.Map.prototype['entries']) { - exports.$$iterator = key; - break; + // NOTE: overriding `error` instead of `_error` because we don't want + // to have this flag this subscriber as `isStopped`. We can mimic the + // behavior of the RetrySubscriber (from the `retry` operator), where + // we unsubscribe from our source chain, reset our Subscriber flags, + // then subscribe to the selector result. + CatchSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var result = void 0; + try { + result = this.selector(err, this.caught); } + catch (err2) { + _super.prototype.error.call(this, err2); + return; + } + this._unsubscribeAndRecycle(); + this.add(subscribeToResult_1.subscribeToResult(this, result)); } - } - else { - exports.$$iterator = '@@iterator'; - } -} - -},{"../util/root":153}],141:[function(require,module,exports){ -"use strict"; -var root_1 = require('../util/root'); -function getSymbolObservable(context) { - var $$observable; - var Symbol = context.Symbol; - if (typeof Symbol === 'function') { - if (Symbol.observable) { - $$observable = Symbol.observable; - } - else { - $$observable = Symbol('observable'); - Symbol.observable = $$observable; - } - } - else { - $$observable = '@@observable'; - } - return $$observable; -} -exports.getSymbolObservable = getSymbolObservable; -exports.$$observable = getSymbolObservable(root_1.root); - -},{"../util/root":153}],142:[function(require,module,exports){ -"use strict"; -var root_1 = require('../util/root'); -var Symbol = root_1.root.Symbol; -exports.$$rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ? - Symbol.for('rxSubscriber') : '@@rxSubscriber'; + }; + return CatchSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); -},{"../util/root":153}],143:[function(require,module,exports){ +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],164:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; +var ArrayObservable_1 = require('../observable/ArrayObservable'); +var isArray_1 = require('../util/isArray'); +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +var none = {}; +/* tslint:enable:max-line-length */ /** - * An error thrown when an element was queried at a certain index of an - * Observable, but no such index or position exists in that sequence. + * Combines multiple Observables to create an Observable whose values are + * calculated from the latest values of each of its input Observables. * - * @see {@link elementAt} - * @see {@link take} - * @see {@link takeLast} + * Whenever any input Observable emits a value, it + * computes a formula using the latest values from all the inputs, then emits + * the output of that formula. * - * @class ArgumentOutOfRangeError - */ -var ArgumentOutOfRangeError = (function (_super) { - __extends(ArgumentOutOfRangeError, _super); - function ArgumentOutOfRangeError() { - var err = _super.call(this, 'argument out of range'); - this.name = err.name = 'ArgumentOutOfRangeError'; - this.stack = err.stack; - this.message = err.message; - } - return ArgumentOutOfRangeError; -}(Error)); -exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError; - -},{}],144:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -/** - * An error thrown when an Observable or a sequence was queried but has no - * elements. + * * - * @see {@link first} - * @see {@link last} - * @see {@link single} + * `combineLatest` combines the values from this Observable with values from + * Observables passed as arguments. This is done by subscribing to each + * Observable, in order, and collecting an array of each of the most recent + * values any time any of the input Observables emits, then either taking that + * array and passing it as arguments to an optional `project` function and + * emitting the return value of that, or just emitting the array of recent + * values directly if there is no `project` function. * - * @class EmptyError - */ -var EmptyError = (function (_super) { - __extends(EmptyError, _super); - function EmptyError() { - var err = _super.call(this, 'no elements in sequence'); - this.name = err.name = 'EmptyError'; - this.stack = err.stack; - this.message = err.message; - } - return EmptyError; -}(Error)); -exports.EmptyError = EmptyError; - -},{}],145:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -/** - * An error thrown when an action is invalid because the object has been - * unsubscribed. + * @example Dynamically calculate the Body-Mass Index from an Observable of weight and one for height + * var weight = Rx.Observable.of(70, 72, 76, 79, 75); + * var height = Rx.Observable.of(1.76, 1.77, 1.78); + * var bmi = weight.combineLatest(height, (w, h) => w / (h * h)); + * bmi.subscribe(x => console.log('BMI is ' + x)); * - * @see {@link Subject} - * @see {@link BehaviorSubject} + * // With output to console: + * // BMI is 24.212293388429753 + * // BMI is 23.93948099205209 + * // BMI is 23.671253629592222 * - * @class ObjectUnsubscribedError + * @see {@link combineAll} + * @see {@link merge} + * @see {@link withLatestFrom} + * + * @param {ObservableInput} other An input Observable to combine with the source + * Observable. More than one input Observables may be given as argument. + * @param {function} [project] An optional function to project the values from + * the combined latest values into a new value on the output Observable. + * @return {Observable} An Observable of projected values from the most recent + * values from each input Observable, or an array of the most recent values from + * each input Observable. + * @method combineLatest + * @owner Observable */ -var ObjectUnsubscribedError = (function (_super) { - __extends(ObjectUnsubscribedError, _super); - function ObjectUnsubscribedError() { - var err = _super.call(this, 'object unsubscribed'); - this.name = err.name = 'ObjectUnsubscribedError'; - this.stack = err.stack; - this.message = err.message; +function combineLatest() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; } - return ObjectUnsubscribedError; -}(Error)); -exports.ObjectUnsubscribedError = ObjectUnsubscribedError; - -},{}],146:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -/** - * An error thrown when one or more errors have occurred during the - * `unsubscribe` of a {@link Subscription}. - */ -var UnsubscriptionError = (function (_super) { - __extends(UnsubscriptionError, _super); - function UnsubscriptionError(errors) { - _super.call(this); - this.errors = errors; - var err = Error.call(this, errors ? - errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : ''); - this.name = err.name = 'UnsubscriptionError'; - this.stack = err.stack; - this.message = err.message; + var project = null; + if (typeof observables[observables.length - 1] === 'function') { + project = observables.pop(); } - return UnsubscriptionError; -}(Error)); -exports.UnsubscriptionError = UnsubscriptionError; - -},{}],147:[function(require,module,exports){ -"use strict"; -// typeof any so that it we don't have to cast when comparing a result to the error object -exports.errorObject = { e: {} }; - -},{}],148:[function(require,module,exports){ -"use strict"; -exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); - -},{}],149:[function(require,module,exports){ -"use strict"; -function isFunction(x) { - return typeof x === 'function'; -} -exports.isFunction = isFunction; - -},{}],150:[function(require,module,exports){ -"use strict"; -function isObject(x) { - return x != null && typeof x === 'object'; -} -exports.isObject = isObject; - -},{}],151:[function(require,module,exports){ -"use strict"; -function isPromise(value) { - return value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; -} -exports.isPromise = isPromise; - -},{}],152:[function(require,module,exports){ -"use strict"; -function isScheduler(value) { - return value && typeof value.schedule === 'function'; -} -exports.isScheduler = isScheduler; - -},{}],153:[function(require,module,exports){ -(function (global){ -"use strict"; -var objectTypes = { - 'boolean': false, - 'function': true, - 'object': true, - 'number': false, - 'string': false, - 'undefined': false -}; -exports.root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window); -var freeGlobal = objectTypes[typeof global] && global; -if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { - exports.root = freeGlobal; + // if the first and only other argument besides the resultSelector is an array + // assume it's been called with `combineLatest([obs1, obs2, obs3], project)` + if (observables.length === 1 && isArray_1.isArray(observables[0])) { + observables = observables[0].slice(); + } + return function (source) { return source.lift.call(new ArrayObservable_1.ArrayObservable([source].concat(observables)), new CombineLatestOperator(project)); }; } - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],154:[function(require,module,exports){ -"use strict"; -var root_1 = require('./root'); -var isArray_1 = require('./isArray'); -var isPromise_1 = require('./isPromise'); -var Observable_1 = require('../Observable'); -var iterator_1 = require('../symbol/iterator'); -var InnerSubscriber_1 = require('../InnerSubscriber'); -var observable_1 = require('../symbol/observable'); -function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) { - var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex); - if (destination.closed) { - return null; +exports.combineLatest = combineLatest; +var CombineLatestOperator = (function () { + function CombineLatestOperator(project) { + this.project = project; } - if (result instanceof Observable_1.Observable) { - if (result._isScalar) { - destination.next(result.value); - destination.complete(); - return null; + CombineLatestOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CombineLatestSubscriber(subscriber, this.project)); + }; + return CombineLatestOperator; +}()); +exports.CombineLatestOperator = CombineLatestOperator; +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var CombineLatestSubscriber = (function (_super) { + __extends(CombineLatestSubscriber, _super); + function CombineLatestSubscriber(destination, project) { + _super.call(this, destination); + this.project = project; + this.active = 0; + this.values = []; + this.observables = []; + } + CombineLatestSubscriber.prototype._next = function (observable) { + this.values.push(none); + this.observables.push(observable); + }; + CombineLatestSubscriber.prototype._complete = function () { + var observables = this.observables; + var len = observables.length; + if (len === 0) { + this.destination.complete(); } else { - return result.subscribe(destination); - } - } - if (isArray_1.isArray(result)) { - for (var i = 0, len = result.length; i < len && !destination.closed; i++) { - destination.next(result[i]); + this.active = len; + this.toRespond = len; + for (var i = 0; i < len; i++) { + var observable = observables[i]; + this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i)); + } } - if (!destination.closed) { - destination.complete(); + }; + CombineLatestSubscriber.prototype.notifyComplete = function (unused) { + if ((this.active -= 1) === 0) { + this.destination.complete(); } - } - else if (isPromise_1.isPromise(result)) { - result.then(function (value) { - if (!destination.closed) { - destination.next(value); - destination.complete(); - } - }, function (err) { return destination.error(err); }) - .then(null, function (err) { - // Escaping the Promise trap: globally throw unhandled errors - root_1.root.setTimeout(function () { throw err; }); - }); - return destination; - } - else if (typeof result[iterator_1.$$iterator] === 'function') { - var iterator = result[iterator_1.$$iterator](); - do { - var item = iterator.next(); - if (item.done) { - destination.complete(); - break; + }; + CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + var values = this.values; + var oldVal = values[outerIndex]; + var toRespond = !this.toRespond + ? 0 + : oldVal === none ? --this.toRespond : this.toRespond; + values[outerIndex] = innerValue; + if (toRespond === 0) { + if (this.project) { + this._tryProject(values); } - destination.next(item.value); - if (destination.closed) { - break; + else { + this.destination.next(values.slice()); } - } while (true); - } - else if (typeof result[observable_1.$$observable] === 'function') { - var obs = result[observable_1.$$observable](); - if (typeof obs.subscribe !== 'function') { - destination.error(new Error('invalid observable')); } - else { - return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex)); + }; + CombineLatestSubscriber.prototype._tryProject = function (values) { + var result; + try { + result = this.project.apply(this, values); } - } - else { - destination.error(new TypeError('unknown type returned')); - } - return null; -} -exports.subscribeToResult = subscribeToResult; + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return CombineLatestSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); +exports.CombineLatestSubscriber = CombineLatestSubscriber; -},{"../InnerSubscriber":26,"../Observable":28,"../symbol/iterator":140,"../symbol/observable":141,"./isArray":148,"./isPromise":151,"./root":153}],155:[function(require,module,exports){ +},{"../OuterSubscriber":31,"../observable/ArrayObservable":93,"../util/isArray":226,"../util/subscribeToResult":237}],165:[function(require,module,exports){ "use strict"; -var Subscriber_1 = require('../Subscriber'); -var rxSubscriber_1 = require('../symbol/rxSubscriber'); -function toSubscriber(nextOrObserver, error, complete) { - if (nextOrObserver) { - if (nextOrObserver instanceof Subscriber_1.Subscriber) { - return nextOrObserver; - } - if (nextOrObserver[rxSubscriber_1.$$rxSubscriber]) { - return nextOrObserver[rxSubscriber_1.$$rxSubscriber](); - } - } - if (!nextOrObserver && !error && !complete) { - return new Subscriber_1.Subscriber(); +var concat_1 = require('../observable/concat'); +/* tslint:enable:max-line-length */ +/** + * Creates an output Observable which sequentially emits all values from every + * given input Observable after the current Observable. + * + * Concatenates multiple Observables together by + * sequentially emitting their values, one Observable after the other. + * + * + * + * Joins this Observable with multiple other Observables by subscribing to them + * one at a time, starting with the source, and merging their results into the + * output Observable. Will wait for each Observable to complete before moving + * on to the next. + * + * @example Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10 + * var timer = Rx.Observable.interval(1000).take(4); + * var sequence = Rx.Observable.range(1, 10); + * var result = timer.concat(sequence); + * result.subscribe(x => console.log(x)); + * + * // results in: + * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10 + * + * @example Concatenate 3 Observables + * var timer1 = Rx.Observable.interval(1000).take(10); + * var timer2 = Rx.Observable.interval(2000).take(6); + * var timer3 = Rx.Observable.interval(500).take(10); + * var result = timer1.concat(timer2, timer3); + * result.subscribe(x => console.log(x)); + * + * // results in the following: + * // (Prints to console sequentially) + * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9 + * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5 + * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9 + * + * @see {@link concatAll} + * @see {@link concatMap} + * @see {@link concatMapTo} + * + * @param {ObservableInput} other An input Observable to concatenate after the source + * Observable. More than one input Observables may be given as argument. + * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each + * Observable subscription on. + * @return {Observable} All values of each passed Observable merged into a + * single Observable, in order, in serial fashion. + * @method concat + * @owner Observable + */ +function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; } - return new Subscriber_1.Subscriber(nextOrObserver, error, complete); + return function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); }; } -exports.toSubscriber = toSubscriber; +exports.concat = concat; -},{"../Subscriber":35,"../symbol/rxSubscriber":142}],156:[function(require,module,exports){ +},{"../observable/concat":105}],166:[function(require,module,exports){ "use strict"; -var errorObject_1 = require('./errorObject'); -var tryCatchTarget; -function tryCatcher() { - try { - return tryCatchTarget.apply(this, arguments); - } - catch (e) { - errorObject_1.errorObject.e = e; - return errorObject_1.errorObject; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} -exports.tryCatch = tryCatch; -; - -},{"./errorObject":147}],157:[function(require,module,exports){ -// threejs.org/license -(function(l,sa){"object"===typeof exports&&"undefined"!==typeof module?sa(exports):"function"===typeof define&&define.amd?define(["exports"],sa):sa(l.THREE=l.THREE||{})})(this,function(l){function sa(){}function B(a,b){this.x=a||0;this.y=b||0}function da(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:ee++});this.uuid=T.generateUUID();this.sourceFile=this.name="";this.image=void 0!==a?a:da.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:da.DEFAULT_MAPPING;this.wrapS=void 0!==c? -c:1001;this.wrapT=void 0!==d?d:1001;this.magFilter=void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new B(0,0);this.repeat=new B(1,1);this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==m?m:3E3;this.version=0;this.onUpdate=null}function ga(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Db(a,b,c){this.uuid=T.generateUUID(); -this.width=a;this.height=b;this.scissor=new ga(0,0,a,b);this.scissorTest=!1;this.viewport=new ga(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new da(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Eb(a,b,c){Db.call(this,a,b,c);this.activeMipMapLevel= -this.activeCubeFace=0}function ba(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function q(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function J(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);0= -d||0 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n")); -y.compileShader(P);y.compileShader(R);y.attachShader(N,P);y.attachShader(N,R);y.linkProgram(N);M=N;u=y.getAttribLocation(M,"position");v=y.getAttribLocation(M,"uv");c=y.getUniformLocation(M,"uvOffset");d=y.getUniformLocation(M,"uvScale");e=y.getUniformLocation(M,"rotation");f=y.getUniformLocation(M,"scale");g=y.getUniformLocation(M,"color");h=y.getUniformLocation(M,"map");k=y.getUniformLocation(M,"opacity");m=y.getUniformLocation(M,"modelViewMatrix");w=y.getUniformLocation(M,"projectionMatrix");n= -y.getUniformLocation(M,"fogType");p=y.getUniformLocation(M,"fogDensity");r=y.getUniformLocation(M,"fogNear");x=y.getUniformLocation(M,"fogFar");l=y.getUniformLocation(M,"fogColor");D=y.getUniformLocation(M,"alphaTest");N=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");N.width=8;N.height=8;P=N.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);ca=new da(N);ca.needsUpdate=!0}y.useProgram(M);E.initAttributes();E.enableAttribute(u);E.enableAttribute(v);E.disableUnusedAttributes(); -E.disable(y.CULL_FACE);E.enable(y.BLEND);y.bindBuffer(y.ARRAY_BUFFER,H);y.vertexAttribPointer(u,2,y.FLOAT,!1,16,0);y.vertexAttribPointer(v,2,y.FLOAT,!1,16,8);y.bindBuffer(y.ELEMENT_ARRAY_BUFFER,F);y.uniformMatrix4fv(w,!1,Ka.projectionMatrix.elements);E.activeTexture(y.TEXTURE0);y.uniform1i(h,0);P=N=0;(R=q.fog)?(y.uniform3f(l,R.color.r,R.color.g,R.color.b),R&&R.isFog?(y.uniform1f(r,R.near),y.uniform1f(x,R.far),y.uniform1i(n,1),P=N=1):R&&R.isFogExp2&&(y.uniform1f(p,R.density),y.uniform1i(n,2),P=N=2)): -(y.uniform1i(n,0),P=N=0);for(var R=0,S=b.length;R/g,function(a,c){var d=X[c];if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Cd(d)})}function ve(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);cb||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a} -function k(a){return T.isPowerOfTwo(a.width)&&T.isPowerOfTwo(a.height)}function m(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function w(b){b=b.target;b.removeEventListener("dispose",w);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d["delete"](b)}q.textures--}function n(b){b=b.target;b.removeEventListener("dispose",n);var c=d.get(b),e=d.get(b.texture);if(b){void 0!== -e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b&&b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d["delete"](b.texture);d["delete"](b)}q.textures--}function p(b,g){var m=d.get(b);if(0x;x++)l[x]=p||n?n?b.image[x].image:b.image[x]:h(b.image[x],e.maxCubemapSize);var t=k(l[0]),u=f(b.format),ja=f(b.type);r(a.TEXTURE_CUBE_MAP, -b,t);for(x=0;6>x;x++)if(p)for(var B,C=l[x].mipmaps,z=0,N=C.length;zm;m++)e.__webglFramebuffer[m]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(g){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);r(a.TEXTURE_CUBE_MAP,b.texture,h);for(m=0;6>m;m++)l(e.__webglFramebuffer[m],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+m);b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP, -null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),r(a.TEXTURE_2D,b.texture,h),l(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=b&&b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER, -e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);p(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER, -a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),t(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),t(e.__webglDepthbuffer, -b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture;e.generateMipmaps&&k(b)&&1003!==e.minFilter&&1006!==e.minFilter&&(b=b&&b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function xf(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},"delete":function(b){delete a[b.uuid]},clear:function(){a={}}}}function yf(a,b,c){function d(b, -c,d){var e=new Uint8Array(4),f=a.createTexture();a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b=ia.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+ia.maxTextures);da+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."), -a=!0),b=b.texture);ua.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);ua.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&& -6===b.image.length?ua.setTextureCube(b,c):ua.setTextureCubeDynamic(b,c)}}();this.getCurrentRenderTarget=function(){return V};this.setRenderTarget=function(a){(V=a)&&void 0===ea.get(a).__webglFramebuffer&&ua.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,c;a?(c=ea.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,X.copy(a.scissor),fb=a.scissorTest,$a.copy(a.viewport)):(c=null,X.copy(ha).multiplyScalar(Qa),fb=la,$a.copy(fa).multiplyScalar(Qa));T!==c&&(A.bindFramebuffer(A.FRAMEBUFFER, -c),T=c);Y.scissor(X);Y.setScissorTest(fb);Y.viewport($a);b&&(b=ea.get(a.texture),A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(!1===(a&&a.isWebGLRenderTarget))console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");else{var g=ea.get(a).__webglFramebuffer;if(g){var h=!1;g!==T&&(A.bindFramebuffer(A.FRAMEBUFFER, -g),h=!0);try{var k=a.texture,m=k.format,n=k.type;1023!==m&&u(m)!==A.getParameter(A.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||u(n)===A.getParameter(A.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ka.get("OES_texture_float")||ka.get("WEBGL_color_buffer_float"))||1016===n&&ka.get("EXT_color_buffer_half_float")?A.checkFramebufferStatus(A.FRAMEBUFFER)===A.FRAMEBUFFER_COMPLETE?0<=b&& -b<=a.width-d&&0<=c&&c<=a.height-e&&A.readPixels(b,c,d,e,u(m),u(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&A.bindFramebuffer(A.FRAMEBUFFER,T)}}}}}function Ib(a,b){this.name="";this.color=new O(a);this.density=void 0!==b?b:2.5E-4}function Jb(a,b,c){this.name="";this.color= -new O(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function jb(){z.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Ed(a,b,c,d,e){z.call(this);this.lensFlares=[];this.positionScreen=new q;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function kb(a){U.call(this);this.type="SpriteMaterial";this.color=new O(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function qc(a){z.call(this); -this.type="Sprite";this.material=void 0!==a?a:new kb}function rc(){z.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function lb(a,b,c,d,e,f,g,h,k,m,w,n){da.call(this,null,f,g,h,k,m,d,e,w,n);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==m?m:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function bd(a,b,c){this.useVertexTexture=void 0!==c?c:!0;this.identityMatrix=new J;a=a||[];this.bones=a.slice(0); -this.useVertexTexture?(a=Math.sqrt(4*this.bones.length),a=T.nextPowerOfTwo(Math.ceil(a)),this.boneTextureHeight=this.boneTextureWidth=a=Math.max(a,4),this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new lb(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,1023,1015)):this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton bonInverses is the wrong length."), -this.boneInverses=[],b=0,a=this.bones.length;b=a.HAVE_CURRENT_DATA&&(w.needsUpdate=!0)}da.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var w=this;m()}function Lb(a,b,c,d,e,f,g,h,k,m,w,n){da.call(this,null,f,g,h,k,m,d,e,w,n);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function fd(a,b,c,d,e,f,g,h,k){da.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function tc(a,b,c,d,e,f,g, -h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");da.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,height:b};this.type=void 0!==c?c:1012;this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Mb(a){function b(a,b){return a-b}G.call(this);var c=[0,0],d={},e=["a","b","c"];if(a&&a.isGeometry){var f=a.vertices,g=a.faces,h=0,k=new Uint32Array(6*g.length); -a=0;for(var m=g.length;an;n++){c[0]=w[e[n]];c[1]=w[e[(n+1)%3]];c.sort(b);var p=c.toString();void 0===d[p]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[p]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;an;n++)d=f[k[2*a+n]],h=6*a+3*n,c[h+0]=d.x,c[h+1]=d.y,c[h+2]=d.z;this.addAttribute("position",new C(c,3))}else if(a&&a.isBufferGeometry){if(null!==a.index){m=a.index.array;f=a.attributes.position;e=a.groups;h=0;0===e.length&&a.addGroup(0,m.length);k=new Uint32Array(2*m.length); -g=0;for(w=e.length;gn;n++)c[0]=m[a+n],c[1]=m[a+(n+1)%3],c.sort(b),p=c.toString(),void 0===d[p]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[p]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;an;n++)h=6*a+3*n,d=k[2*a+n],c[h+0]=f.getX(d),c[h+1]=f.getY(d),c[h+2]=f.getZ(d)}else for(f=a.attributes.position.array,h=f.length/3,k=h/3,c=new Float32Array(6*h),a=0,m=k;an;n++)h=18*a+6*n,k=9*a+3*n,c[h+0]=f[k],c[h+1]=f[k+1], -c[h+2]=f[k+2],d=9*a+(n+1)%3*3,c[h+3]=f[d],c[h+4]=f[d+1],c[h+5]=f[d+2];this.addAttribute("position",new C(c,3))}}function Nb(a,b,c){G.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f,g,h,k,m,w=b+1;for(f=0;f<=c;f++)for(m=f/c,g=0;g<=b;g++)k=g/b,h=a(k,m),d.push(h.x,h.y,h.z),e.push(k,m);a=[];var n;for(f=0;fd&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===c.z&&(k[b]=d/2/Math.PI+.5)}G.call(this);this.type="PolyhedronBufferGeometry";this.parameters= -{vertices:a,indices:b,radius:c,detail:d};c=c||1;var h=[],k=[];(function(a){for(var c=new q,d=new q,g=new q,h=0;he&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",ha(h,3));this.addAttribute("normal",ha(h.slice(),3));this.addAttribute("uv",ha(k,2));this.normalizeNormals();this.boundingSphere=new Ca(new q, -c)}function Ob(a,b){ua.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function vc(a,b){Q.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function Pb(a,b){ua.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters= -{radius:a,detail:b}}function wc(a,b){Q.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Pb(a,b));this.mergeVertices()}function Qb(a,b){var c=(1+Math.sqrt(5))/2;ua.call(this,[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters= -{radius:a,detail:b}}function xc(a,b){Q.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));this.mergeVertices()}function Rb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;ua.call(this,[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2, -6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function yc(a,b){Q.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Rb(a,b));this.mergeVertices()}function zc(a,b,c,d){Q.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d}; -this.fromBufferGeometry(new ua(a,b,c,d));this.mergeVertices()}function Sb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(n=0;n<=d;n++){var w=n/d*Math.PI*2,l=Math.sin(w),w=-Math.cos(w);k.x=w*m.x+l*e.x;k.y=w*m.y+l*e.y;k.z=w*m.z+l*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=f.x+c*k.x;h.y=f.y+c*k.y;h.z=f.z+c*k.z;p.push(h.x,h.y,h.z)}}G.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c|| -1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new q,k=new q,m=new B,w,n,p=[],r=[],l=[],t=[];for(w=0;wp;p++){e[0]=n[g[p]];e[1]=n[g[(p+1)%3]];e.sort(c);var l=e.toString();void 0===f[l]?f[l]={vert1:e[0],vert2:e[1],face1:m,face2:void 0}:f[l].face2=m}e=[];for(l in f)if(g=f[l],void 0===g.face2||h[g.face1].normal.dot(h[g.face2].normal)<=d)m=k[g.vert1],e.push(m.x),e.push(m.y),e.push(m.z),m=k[g.vert2],e.push(m.x),e.push(m.y),e.push(m.z);this.addAttribute("position",new C(new Float32Array(e),3))}function Ua(a, -b,c,d,e,f,g,h){function k(c){var e,f,k,n=new B,p=new q,l=0,w=!0===c?a:b,I=!0===c?1:-1;f=u;for(e=1;e<=d;e++)x.setXYZ(u,0,y*I,0),t.setXYZ(u,0,I,0),n.x=.5,n.y=.5,D.setXY(u,n.x,n.y),u++;k=u;for(e=0;e<=d;e++){var z=e/d*h+g,C=Math.cos(z),z=Math.sin(z);p.x=w*z;p.y=y*I;p.z=w*C;x.setXYZ(u,p.x,p.y,p.z);t.setXYZ(u,0,I,0);n.x=.5*C+.5;n.y=.5*z*I+.5;D.setXY(u,n.x,n.y);u++}for(e=0;ethis.duration&&this.resetDuration();this.optimize()}function ud(a){this.manager=void 0!==a?a:Ga;this.textures={}}function Id(a){this.manager=void 0!==a?a:Ga}function wb(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function Jd(a){"boolean"=== -typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:Ga;this.withCredentials=!1}function xe(a){this.manager=void 0!==a?a:Ga;this.texturePath=""}function ia(){}function Sa(a,b){this.v1=a;this.v2=b}function Oc(){this.curves=[];this.autoClose=!1}function Va(a,b,c,d,e,f,g,h){this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle=f;this.aClockwise=g;this.aRotation=h||0}function xb(a){this.points= -void 0===a?[]:a}function yb(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d}function zb(a,b,c){this.v0=a;this.v1=b;this.v2=c}function Ab(){Pc.apply(this,arguments);this.holes=[]}function Pc(a){Oc.call(this);this.currentPoint=new B;a&&this.fromPoints(a)}function Kd(){this.subPaths=[];this.currentPath=null}function Ld(a){this.data=a}function ye(a){this.manager=void 0!==a?a:Ga}function Md(){void 0===Nd&&(Nd=new (window.AudioContext||window.webkitAudioContext));return Nd}function Od(a){this.manager= -void 0!==a?a:Ga}function ze(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new Ea;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new Ea;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function vd(a,b,c){z.call(this);this.type="CubeCamera";var d=new Ea(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new q(1,0,0));this.add(d);var e=new Ea(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new q(-1,0,0));this.add(e);var f=new Ea(90,1,a,b);f.up.set(0,0,1);f.lookAt(new q(0, -1,0));this.add(f);var g=new Ea(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new q(0,-1,0));this.add(g);var h=new Ea(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new q(0,0,1));this.add(h);var k=new Ea(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new q(0,0,-1));this.add(k);this.renderTarget=new Eb(c,c,{format:1022,magFilter:1006,minFilter:1006});this.updateCubeMap=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,p=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b, -d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=p;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function Pd(){z.call(this);this.type="AudioListener";this.context=Md();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function dc(a){z.call(this);this.type="Audio";this.context=a.context;this.source=this.context.createBufferSource(); -this.source.onended=this.onEnded.bind(this);this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function Qd(a){dc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function Rd(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount); -a.getOutput().connect(this.analyser)}function wd(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function fa(a,b,c){this.path=b;this.parsedPath=c||fa.parseTrackName(b);this.node=fa.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function Sd(a){this.uuid=T.generateUUID(); -this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==d;++c)b[arguments[c].uuid]=c;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}function Td(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks; -b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled= -!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function Ud(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Ae(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function Bb(){G.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function Vd(a,b,c,d){this.uuid=T.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0=== -d}function ec(a,b){this.uuid=T.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.version=0}function fc(a,b,c){ec.call(this,a,b);this.meshPerAttribute=c||1}function gc(a,b,c){C.call(this,a,b);this.meshPerAttribute=c||1}function Wd(a,b,c,d){this.ray=new ab(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points."); -return this.Points}}})}function Be(a,b){return a.distance-b.distance}function Xd(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;dc;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new ha(b,3));b=new oa({fog:!1});this.cone=new la(a,b);this.add(this.cone);this.update()}function ic(a){this.bones=this.getBoneList(a);for(var b=new Q, -c=0;cd;d++)c.faces[d].color=this.colors[4>d?0:1];d=new Ma({vertexColors:1,wireframe:!0});this.lightSphere=new ya(c,d);this.add(this.lightSphere);this.update()}function Sc(a,b,c,d){b=b||1;c=new O(void 0!==c?c:4473924);d=new O(void 0!== -d?d:8947848);for(var e=b/2,f=2*a/b,g=[],h=[],k=0,m=0,l=-a;k<=b;k++,l+=f){g.push(-a,0,l,a,0,l);g.push(l,0,-a,l,0,a);var n=k===e?c:d;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3}a=new G;a.addAttribute("position",new ha(g,3));a.addAttribute("color",new ha(h,3));g=new oa({vertexColors:2});la.call(this,a,g)}function Tc(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16776960;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead."); -c=new G;b=new ha(6*b,3);c.addAttribute("position",b);la.call(this,c,new oa({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function lc(a,b){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new G;c.addAttribute("position",new ha([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new oa({fog:!1});this.add(new Ta(c,d));c=new G;c.addAttribute("position",new ha([0,0,0,0,0,1],3));this.add(new Ta(c,d));this.update()} -function Uc(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){d.vertices.push(new q);d.colors.push(new O(b));void 0===f[a]&&(f[a]=[]);f[a].push(d.vertices.length-1)}var d=new Q,e=new oa({color:16777215,vertexColors:1}),f={};b("n1","n2",16755200);b("n2","n4",16755200);b("n4","n3",16755200);b("n3","n1",16755200);b("f1","f2",16755200);b("f2","f4",16755200);b("f4","f3",16755200);b("f3","f1",16755200);b("n1","f1",16755200);b("n2","f2",16755200);b("n3","f3",16755200);b("n4","f4",16755200);b("p","n1",16711680); -b("p","n2",16711680);b("p","n3",16711680);b("p","n4",16711680);b("u1","u2",43775);b("u2","u3",43775);b("u3","u1",43775);b("c","t",16777215);b("p","c",3355443);b("cn1","cn2",3355443);b("cn3","cn4",3355443);b("cf1","cf2",3355443);b("cf3","cf4",3355443);la.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=f;this.update()}function Vc(a,b){var c=void 0!==b?b:8947848;this.object=a;this.box= -new Ba;ya.call(this,new ob(1,1,1),new Ma({color:c,wireframe:!0}))}function Wc(a,b){void 0===b&&(b=16776960);var c=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),d=new Float32Array(24),e=new G;e.setIndex(new C(c,1));e.addAttribute("position",new C(d,3));la.call(this,e,new oa({color:b}));void 0!==a&&this.update(a)}function Cb(a,b,c,d,e,f){z.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);this.position.copy(b);this.line=new Ta(Ce,new oa({color:d})); -this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new ya(De,new Ma({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,e,f)}function xd(a){a=a||1;var b=new Float32Array([0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a]),c=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]);a=new G;a.addAttribute("position",new C(b,3));a.addAttribute("color",new C(c,3));b=new oa({vertexColors:2});la.call(this,a,b)}function Ee(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3."); -$d.call(this,a);this.type="catmullrom";this.closed=!0}function yd(a,b,c,d,e,f){Va.call(this,a,b,c,c,d,e,f)}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a, -b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},random16:function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a* -T.DEG2RAD},radToDeg:function(a){return a*T.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}};B.prototype={constructor:B,isVector2:!0,get width(){return this.x},set width(a){this.x=a},get height(){return this.y},set height(a){this.y=a},set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x= -a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!== -b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."), -this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a):this.y=this.x=0;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y, -a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new B,b=new B);a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y= -Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x* -this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.multiplyScalar(a/ -this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+ -1];return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}};da.DEFAULT_IMAGE=void 0;da.DEFAULT_MAPPING=300;da.prototype={constructor:da,isTexture:!0,set needsUpdate(a){!0===a&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=a.magFilter;this.minFilter= -a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping, -repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=this.image;void 0===c.uuid&&(c.uuid=T.generateUUID());if(void 0===a.images[c.uuid]){var d=a.images,e=c.uuid,f=c.uuid,g;void 0!==c.toDataURL?g=c:(g=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),g.width=c.width,g.height=c.height,g.getContext("2d").drawImage(c, -0,0,c.width,c.height));g=2048a.x||1a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0> -a.y||1a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}};Object.assign(da.prototype,sa.prototype);var ee=0;ga.prototype={constructor:ga,isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a; -return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x, -this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this}, -addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){isFinite(a)? -(this.x*=a,this.y*=a,this.z*=a,this.w*=a):this.w=this.z=this.y=this.x=0;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y= -0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var m=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01>Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+m-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;m=(m+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>m?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b): -h>m?.01>h?(b=.707106781,c=0,d=.707106781):(c=Math.sqrt(h),b=d/c,d=k/c):.01>m?(c=b=.707106781,d=0):(d=Math.sqrt(m),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x); -this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new ga,b=new ga);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y); -this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z); -this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}, -normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w= -a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];this.w=a.array[b+3];return this}};Object.assign(Db.prototype,sa.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0, -0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Eb.prototype=Object.create(Db.prototype);Eb.prototype.constructor=Eb;Eb.prototype.isWebGLRenderTargetCube=!0;ba.prototype={constructor:ba,get x(){return this._x}, -set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get w(){return this._w},set w(a){this._w=a;this.onChangeCallback()},set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback(); -return this},setFromEuler:function(a,b){if(!1===(a&&a.isEuler))throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=Math.cos(a._x/2),d=Math.cos(a._y/2),e=Math.cos(a._z/2),f=Math.sin(a._x/2),g=Math.sin(a._y/2),h=Math.sin(a._z/2),k=a.order;"XYZ"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e-f*g*h):"YXZ"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e+f*g*h):"ZXY"===k?(this._x= -f*d*e-c*g*h,this._y=c*g*e+f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e-f*g*h):"ZYX"===k?(this._x=f*d*e-c*g*h,this._y=c*g*e+f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e+f*g*h):"YZX"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e+f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e-f*g*h):"XZY"===k&&(this._x=f*d*e-c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e+f*g*h);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);this._x=a.x*d;this._y=a.y*d;this._z=a.z*d;this._w= -Math.cos(c);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],m=c+f+b;0f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+ -h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a,b;return function(c,d){void 0===a&&(a=new q);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x* -a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."), -this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z; -0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x=== -this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};Object.assign(ba,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a, -b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var l=e[f+1],n=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==l||m!==n){f=1-g;var p=h*d+k*l+m*n+c*e,r=0<=p?1:-1,x=1-p*p;x>Number.EPSILON&&(x=Math.sqrt(x),p=Math.atan2(x,p*r),f=Math.sin(f*p)/x,g=Math.sin(g*p)/x);r*=g;h=h*f+d*r;k=k*f+l*r;m=m*f+n*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});q.prototype={constructor:q,isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this}, -setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x, -this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+= -a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."), -this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a):this.z=this.y=this.x=0;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a;return function(b){!1===(b&&b.isEuler)&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");void 0===a&&(a=new ba);return this.applyQuaternion(a.setFromEuler(b))}}(), -applyAxisAngle:function(){var a;return function(b,c){void 0===a&&(a=new ba);return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12];this.y=a[1]*b+a[5]*c+a[9]*d+a[13];this.z=a[2]*b+a[6]*c+a[10]*d+a[14];return this},applyProjection:function(a){var b= -this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*-g+h*-f-k*-e;return this},project:function(){var a;return function(b){void 0===a&&(a=new J); -a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyProjection(a)}}(),unproject:function(){var a;return function(b){void 0===a&&(a=new J);a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyProjection(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/= -a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a,b;return function(c, -d){void 0===a&&(a=new q,b=new q);a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this}, -roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+ -Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a, -b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=e*f-c*h;this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a;return function(b){void 0===a&&(a=new q);a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a;return function(b){void 0=== -a&&(a=new q);return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(T.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius; -this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){return this.setFromMatrixColumn(a,3)},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){if("number"===typeof a){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index )."); -var c=a;a=b;b=c}return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];return this}};J.prototype={constructor:J,isMatrix4:!0, -set:function(a,b,c,d,e,f,g,h,k,m,l,n,p,r,x,t){var q=this.elements;q[0]=a;q[4]=b;q[8]=c;q[12]=d;q[1]=e;q[5]=f;q[9]=g;q[13]=h;q[2]=k;q[6]=m;q[10]=l;q[14]=n;q[3]=p;q[7]=r;q[11]=x;q[15]=t;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new J).fromArray(this.elements)},copy:function(a){this.elements.set(a.elements);return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a, -b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a;return function(b){void 0===a&&(a=new q);var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]* -f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){!1===(a&&a.isEuler)&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,l=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-l*d;b[9]=-c*g;b[2]=l-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"=== -a.order?(a=g*h,k=g*e,m=d*h,l=d*e,b[0]=a+l*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=l+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,l=d*e,b[0]=a-l*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=l-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,l=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*d+l,b[1]=g*e,b[5]=l*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,l=c*d,b[0]=g*h,b[4]=l-a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k* -e+m,b[10]=a-l*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,l=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+l,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=l*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=this.elements,c=a.x,d=a.y,e=a.z,f=a.w,g=c+c,h=d+d,k=e+e;a=c*g;var m=c*h,c=c*k,l=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(l+e);b[4]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+l);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]= -0;b[14]=0;b[15]=1;return this},lookAt:function(){var a,b,c;return function(d,e,f){void 0===a&&(a=new q,b=new q,c=new q);var g=this.elements;c.subVectors(d,e).normalize();0===c.lengthSq()&&(c.z=1);a.crossVectors(f,c).normalize();0===a.lengthSq()&&(c.z+=1E-4,a.crossVectors(f,c).normalize());b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."), -this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=c[1],l=c[5],n=c[9],p=c[13],r=c[2],x=c[6],t=c[10],q=c[14],u=c[3],v=c[7],I=c[11],c=c[15],y=d[0],E=d[4],H=d[8],F=d[12],M=d[1],B=d[5],K=d[9],z=d[13],C=d[2],G=d[6],J=d[10],N=d[14],P=d[3],R=d[7],S=d[11],d=d[15];e[0]=f*y+g*M+h*C+k*P;e[4]=f*E+g*B+h*G+k*R;e[8]=f*H+g*K+h*J+k*S;e[12]= -f*F+g*z+h*N+k*d;e[1]=m*y+l*M+n*C+p*P;e[5]=m*E+l*B+n*G+p*R;e[9]=m*H+l*K+n*J+p*S;e[13]=m*F+l*z+n*N+p*d;e[2]=r*y+x*M+t*C+q*P;e[6]=r*E+x*B+t*G+q*R;e[10]=r*H+x*K+t*J+q*S;e[14]=r*F+x*z+t*N+q*d;e[3]=u*y+v*M+I*C+c*P;e[7]=u*E+v*B+I*G+c*R;e[11]=u*H+v*K+I*J+c*S;e[15]=u*F+v*z+I*N+c*d;return this},multiplyToArray:function(a,b,c){var d=this.elements;this.multiplyMatrices(a,b);c[0]=d[0];c[1]=d[1];c[2]=d[2];c[3]=d[3];c[4]=d[4];c[5]=d[5];c[6]=d[6];c[7]=d[7];c[8]=d[8];c[9]=d[9];c[10]=d[10];c[11]=d[11];c[12]=d[12]; -c[13]=d[13];c[14]=d[14];c[15]=d[15];return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToVector3Array:function(){var a;return function(b,c,d){void 0===a&&(a=new q);void 0===c&&(c=0);void 0===d&&(d=b.length);for(var e=0;ethis.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.elements.set(this.elements);c=1/g;var f=1/h,m=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makeFrustum:function(a,b,c,d,e,f){var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(d-c); -g[9]=(d+c)/(d-c);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makePerspective:function(a,b,c,d){a=c*Math.tan(T.DEG2RAD*a*.5);var e=-a;return this.makeFrustum(e*b,a*b,e,a,c,d)},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b= -this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}};Xa.prototype=Object.create(da.prototype); -Xa.prototype.constructor=Xa;Xa.prototype.isCubeTexture=!0;Object.defineProperty(Xa.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var ie=new da,je=new Xa,fe=[],he=[];ne.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var zd=/([\w\d_]+)(\])?(\[|\.)?/g;Ya.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};Ya.prototype.set=function(a,b,c){var d=this.map[c]; -void 0!==d&&d.setValue(a,b[c],this.renderer)};Ya.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};Ya.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};Ya.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var La={merge:function(a){for(var b={},c=0;c 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n", -bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n", -clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n", -clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n", -color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n", -cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n", -defaultnormal_vertex:"#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n", -emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n",encodings_fragment:" gl_FragColor = linearToOutputTexel( gl_FragColor );\n",encodings_pars_fragment:"\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n", -envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n", -envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n", -envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n",envmap_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n", -fog_fragment:"#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif", -lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n", -lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\t#include \n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\t#include \n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n", -lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n", -lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n", -lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n", -lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n", -logdepthbuf_fragment:"#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n", -map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n", -metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n", -morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n", -normal_flip:"#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n",normal_fragment:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n", -normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n", -packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n", -premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",project_vertex:"#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n", -roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n", -shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n", -shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n", -shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n", -skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n", -skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n", -specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n", -uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n", -uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif", -uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n", -cube_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n", -depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -distanceRGBA_frag:"uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include \n#include \n#include \nvoid main () {\n\t#include \n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n",distanceRGBA_vert:"varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition;\n}\n", -equirect_frag:"uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n", -linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n}\n",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include \n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}\n", -meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshphysical_vert:"#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n}\n", -normal_frag:"uniform float opacity;\nvarying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include \n}\n",normal_vert:"varying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -shadow_frag:"uniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n",shadow_vert:"#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"};O.prototype={constructor:O, -isColor:!0,r:1,g:1,b:1,set:function(a){a&&a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b, -c,d){b=T.euclideanModulo(b,1);c=T.clamp(c,0,1);d=T.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r= -Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d=parseFloat(c[1])/ -360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0=h?k/(e+f): -k/(2-e-f);switch(e){case b:g=(c-d)/k+(cthis.max.x||a.ythis.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&& -this.min.y<=a.min.y&&a.max.y<=this.max.y?!0:!1},getParameter:function(a,b){return(b||new B).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y?!1:!0},clampPoint:function(a,b){return(b||new B).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new B;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min); -this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};U.prototype={constructor:U,isMaterial:!0,get needsUpdate(){return this._needsUpdate},set needsUpdate(a){!0===a&&this.update();this._needsUpdate=a},setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+ -b+"' parameter is undefined.");else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.4,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type; -""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&& -(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale, -d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity= -this.reflectivity);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);2!==this.shading&&(d.shading=this.shading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0e&&(e=m);l>f&&(f=l);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g)},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y|| -a.zthis.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z?!0:!1},getParameter:function(a,b){return(b||new q).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y||a.max.zthis.max.z?!1:!0},intersectsSphere:function(){var a;return function(b){void 0===a&&(a=new q);this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0=a.constant},clampPoint:function(a,b){return(b||new q).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new q;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new q;return function(b){b=b||new Ca;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max); -this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new q,new q,new q,new q,new q,new q,new q,new q];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x, -this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};Ca.prototype={constructor:Ca,set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a= -new Ba;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)- -this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new q;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a= -a||new Ba;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}};Ia.prototype={constructor:Ia,isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1, -0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){a=a.elements;this.set(a[0],a[3],a[6],a[1],a[4],a[7],a[2],a[5],a[8]);return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToVector3Array:function(){var a;return function(b,c,d){void 0===a&&(a=new q);void 0===c&&(c=0);void 0===d&&(d=b.length);for(var e=0;ec;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}};va.prototype={constructor:va,set:function(a,b){this.normal.copy(a); -this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=new q,b=new q;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal); -this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a);return(b|| -new q).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new q;return function(b,c){var d=c||new q,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=-(b.start.dot(this.normal)+this.constant)/f,0>f||1b&&0a&&0c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],m=c[7],l=c[8],n=c[9],p=c[10],r=c[11],q=c[12],t=c[13],D=c[14],c=c[15]; -b[0].setComponents(f-a,m-g,r-l,c-q).normalize();b[1].setComponents(f+a,m+g,r+l,c+q).normalize();b[2].setComponents(f+d,m+h,r+n,c+t).normalize();b[3].setComponents(f-d,m-h,r-n,c-t).normalize();b[4].setComponents(f-e,m-k,r-p,c-D).normalize();b[5].setComponents(f+e,m+k,r+p,c+D).normalize();return this},intersectsObject:function(){var a=new Ca;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(), -intersectsSprite:function(){var a=new Ca;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)e;e++){var f=d[e];a.x=0g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}};ab.prototype={constructor:ab,set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin); -this.direction.copy(a.direction);return this},at:function(a,b){return(b||new q).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=new q;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,b){var c=b||new q;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)}, -distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new q;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new q,b=new q,c=new q;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a); -var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),n=c.lengthSq(),p=Math.abs(1-k*k),r;0=-r?e<=r?(h=1/p,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*l)+n):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):e<=-r?(d=Math.max(0,-(-k*h+m)),e=0f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<= -a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z; -var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;if(fg||e>d)return null;if(e>c||c!==c)c=e;if(gd?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new q;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a= -new q,b=new q,c=new q,d=new q;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.direction.add(this.origin).applyMatrix4(a);this.origin.applyMatrix4(a); -this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}};bb.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");bb.DefaultOrder="XYZ";bb.prototype={constructor:bb,isEuler:!0,get x(){return this._x},set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get order(){return this._order}, -set order(a){this._order=a;this.onChangeCallback()},set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=T.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],l=e[2],n=e[6],e=e[10];b=b|| -this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(n,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-l,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(n,-1,1)),.99999>Math.abs(n)?(this._y=Math.atan2(-l,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),.99999> -Math.abs(l)?(this._x=Math.atan2(n,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-l,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(n,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback(); -return this},setFromQuaternion:function(){var a;return function(b,c,d){void 0===a&&(a=new J);a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new ba;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1]; -this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new q(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};Yc.prototype={constructor:Yc,set:function(a){this.mask=1<=b.x+b.y}}();wa.prototype={constructor:wa,set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c); -return this},area:function(){var a=new q,b=new q;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new q).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return wa.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new va).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return wa.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return wa.containsPoint(a, -this.a,this.b,this.c)},closestPointToPoint:function(){var a,b,c,d;return function(e,f){void 0===a&&(a=new va,b=[new gb,new gb,new gb],c=new q,d=new q);var g=f||new q,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;kd;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e,1),c=0,g=this.faceVertexUvs.length;cb.far?null:{distance:c,point:u.clone(),object:a}}function c(c,d,e,f,m,l,n,w){g.fromArray(f,3*l);h.fromArray(f,3*n);k.fromArray(f, -3*w);if(c=b(c,d,e,g,h,k,D))m&&(p.fromArray(m,2*l),r.fromArray(m,2*n),x.fromArray(m,2*w),c.uv=a(D,g,h,k,p,r,x)),c.face=new ea(l,n,w,wa.normal(g,h,k)),c.faceIndex=l;return c}var d=new J,e=new ab,f=new Ca,g=new q,h=new q,k=new q,m=new q,l=new q,n=new q,p=new B,r=new B,x=new B,t=new q,D=new q,u=new q;return function(q,t){var u=this.geometry,E=this.material,H=this.matrixWorld;if(void 0!==E&&(null===u.boundingSphere&&u.computeBoundingSphere(),f.copy(u.boundingSphere),f.applyMatrix4(H),!1!==q.ray.intersectsSphere(f)&& -(d.getInverse(H),e.copy(q.ray).applyMatrix4(d),null===u.boundingBox||!1!==e.intersectsBox(u.boundingBox)))){var F,M;if(u&&u.isBufferGeometry){var B,K,E=u.index,H=u.attributes,u=H.position.array;void 0!==H.uv&&(F=H.uv.array);if(null!==E)for(var H=E.array,z=0,C=H.length;zthis.scale.x*this.scale.y/4||c.push({distance:Math.sqrt(d),point:this.position, -face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});rc.prototype=Object.assign(Object.create(z.prototype),{constructor:rc,copy:function(a){z.prototype.copy.call(this,a,!1);a=a.levels;for(var b=0,c=a.length;b=d[e].distance)d[e- -1].object.visible=!1,d[e].object.visible=!0;else break;for(;ef||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),td.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,x=r.length/3-1;gf||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),td.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld), -index:g,face:null,faceIndex:null,object:this}))}else if(g&&g.isGeometry)for(k=g.vertices,m=k.length,g=0;gf||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),td.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});la.prototype=Object.assign(Object.create(Ta.prototype), -{constructor:la,isLineSegments:!0});xa.prototype=Object.create(U.prototype);xa.prototype.constructor=xa;xa.prototype.isPointsMaterial=!0;xa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Kb.prototype=Object.assign(Object.create(z.prototype),{constructor:Kb,isPoints:!0,raycast:function(){var a=new J,b=new ab,c=new Ca;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a); -if(fd.far||e.push({distance:m,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var m=m/((this.scale.x+this.scale.y+this.scale.z)/3), -l=m*m,m=new q;if(h&&h.isBufferGeometry){var n=h.index,h=h.attributes.position.array;if(null!==n)for(var p=n.array,n=0,r=p.length;nc)return null;var d=[],e=[],f=[],g,h,k;if(0=m--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var l;a:{var n, -p,r,q,t,D,u,v;n=a[e[g]].x;p=a[e[g]].y;r=a[e[h]].x;q=a[e[h]].y;t=a[e[k]].x;D=a[e[k]].y;if(0>=(r-n)*(D-p)-(q-p)*(t-n))l=!1;else{var I,y,E,H,F,M,B,z,C,G;I=t-r;y=D-q;E=n-t;H=p-D;F=r-n;M=q-p;for(l=0;l=-Number.EPSILON&&z>=-Number.EPSILON&&B>=-Number.EPSILON)){l=!1;break a}l=!0}}if(l){d.push([a[e[g]],a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;kNumber.EPSILON){if(0q||q>p)return[];k=m*l-k*n;if(0>k||k>p)return[]}else{if(0c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;cN){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(n=z;nk;k++)l=m[k].x+":"+m[k].y,l=n[l],void 0!==l&&(m[k]=l);return p.concat()},isClockWise:function(a){return 0>ra.area(a)},b2:function(){return function(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}}(),b3:function(){return function(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}}()};za.prototype=Object.create(Q.prototype);za.prototype.constructor= -za;za.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;dNumber.EPSILON){var k=Math.sqrt(h),m=Math.sqrt(d*d+g*g),h=b.x-f/k;b=b.y+e/k;g=((c.x-g/m-h)*g-(c.y+d/m-b)*d)/(e*g-f*d);d=h+e*g-a.x;e=b+f*g-a.y;f= -d*d+e*e;if(2>=f)return new B(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&(a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new B(d/f,e/f)}function e(a,b){var c,d;for(L=a.length;0<=--L;){c=L;d=L-1;0>d&&(d=a.length-1);var e,f=r+2*l;for(e=0;eMath.abs(b.y-c.y)?[new B(b.x,1-b.z),new B(c.x,1-c.z),new B(d.x,1-d.z),new B(e.x,1-e.z)]:[new B(b.y,1-b.z),new B(c.y,1-c.z),new B(d.y,1-d.z),new B(e.y, -1-e.z)]}};Dc.prototype=Object.create(za.prototype);Dc.prototype.constructor=Dc;mb.prototype=Object.create(G.prototype);mb.prototype.constructor=mb;Vb.prototype=Object.create(Q.prototype);Vb.prototype.constructor=Vb;Wb.prototype=Object.create(G.prototype);Wb.prototype.constructor=Wb;Ec.prototype=Object.create(Q.prototype);Ec.prototype.constructor=Ec;Fc.prototype=Object.create(Q.prototype);Fc.prototype.constructor=Fc;Xb.prototype=Object.create(G.prototype);Xb.prototype.constructor=Xb;Gc.prototype=Object.create(Q.prototype); -Gc.prototype.constructor=Gc;cb.prototype=Object.create(Q.prototype);cb.prototype.constructor=cb;cb.prototype.addShapeList=function(a,b){for(var c=0,d=a.length;c=e)break a;else{f=b[1];a=e)break b}d=c;c=0}}for(;c>>1,ab;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),d=this.getValueSize(),this.times=ma.arraySlice(c,e,f),this.values=ma.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("invalid value size in track",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("track is empty", -this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("time is not a valid number",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("out of order keys",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&ma.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("value is not a valid number",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1, -f=a.length-1,g=1;gk.opacity&&(k.transparent=!0);c.setTextures(h);return c.parse(k)}}()};wb.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;cg;g++)p=v[k++],u=D[2*p],p=D[2*p+1],u=new B(u,p),2!==g&&c.faceVertexUvs[d][h].push(u),0!==g&&c.faceVertexUvs[d][h+1].push(u);n&&(n=3*v[k++],r.normal.set(z[n++],z[n++],z[n]),t.normal.copy(r.normal));if(x)for(d=0;4>d;d++)n=3*v[k++],x=new q(z[n++],z[n++],z[n]),2!==d&&r.vertexNormals.push(x),0!==d&&t.vertexNormals.push(x);w&&(w=v[k++],w=y[w],r.color.setHex(w),t.color.setHex(w));if(b)for(d= -0;4>d;d++)w=v[k++],w=y[w],2!==d&&r.vertexColors.push(new O(w)),0!==d&&t.vertexColors.push(new O(w));c.faces.push(r);c.faces.push(t)}else{r=new ea;r.a=v[k++];r.b=v[k++];r.c=v[k++];h&&(h=v[k++],r.materialIndex=h);h=c.faces.length;if(d)for(d=0;dg;g++)p=v[k++],u=D[2*p],p=D[2*p+1],u=new B(u,p),c.faceVertexUvs[d][h].push(u);n&&(n=3*v[k++],r.normal.set(z[n++],z[n++],z[n]));if(x)for(d=0;3>d;d++)n=3*v[k++],x=new q(z[n++],z[n++],z[n]),r.vertexNormals.push(x); -w&&(w=v[k++],r.color.setHex(y[w]));if(b)for(d=0;3>d;d++)w=v[k++],r.vertexColors.push(new O(y[w]));c.faces.push(r)}})(d);(function(){var b=void 0!==a.influencesPerVertex?a.influencesPerVertex:2;if(a.skinWeights)for(var d=0,g=a.skinWeights.length;dk)g=d+1;else if(0b&&(b=0);1Number.EPSILON&&(g.normalize(),c=Math.acos(T.clamp(d[k-1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(T.clamp(e[0].dot(e[a]),-1,1)),c/=a,0=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null}, -getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;cc;)c+=b;for(;c>b;)c-=b;cb.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=Xc.interpolate;return new B(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a))};yb.prototype=Object.create(ia.prototype); -yb.prototype.constructor=yb;yb.prototype.getPoint=function(a){var b=ra.b3;return new B(b(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y))};yb.prototype.getTangent=function(a){var b=Xc.tangentCubicBezier;return(new B(b(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y))).normalize()};zb.prototype=Object.create(ia.prototype);zb.prototype.constructor=zb;zb.prototype.getPoint=function(a){var b=ra.b2;return new B(b(a,this.v0.x, -this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))};zb.prototype.getTangent=function(a){var b=Xc.tangentQuadraticBezier;return(new B(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))).normalize()};var de=Object.assign(Object.create(Oc.prototype),{fromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;bNumber.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.yh.y))if(a.y=== -g.y){if(a.x===g.x)return!0}else{e=l*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=ra.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,l=[];if(1===f.length)return h=f[0],k=new Ab,k.curves=h.curves,l.push(k),l;var q=!e(f[0].getPoints()),q=a?!q:q;k=[];var n=[],p=[],r=0,x;n[r]=void 0;p[r]=[];for(var t=0,D=f.length;td&&this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d= -b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d,e){ba.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}};fa.prototype={constructor:fa,getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a= -this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=fa.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error(" can not bind to material as node does not have a material",this);return}if(!a.material.materials){console.error(" can not bind to material.materials as node.material does not have a materials array", -this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error(" can not bind to bones as node does not have a skeleton",this);return}a=a.skeleton.bones;for(c=0;c=c){var n=c++,p=b[n];d[p.uuid]=q;b[q]=p;d[l]=n;b[n]=k;k=0;for(l=f;k!==l;++k){var p=e[k],r=p[q];p[q]=p[n];p[n]=r}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,q=e[l];if(void 0!== -q)if(delete e[l],qb||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0c.parameterPositions[1]&& -(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this.loopCount= -0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time, -f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}};Object.assign(Ud.prototype,sa.prototype,{clipAction:function(a,b){var c=b||this._root,d=c.uuid,e="string"===typeof a?Ha.findByName(c,a):a,c=null!==e?e.uuid:a,f=this._actionsByClip[c],g=null;if(void 0!==f){g=f.actionByRoot[d];if(void 0!==g)return g;g=f.knownActions[0];null===e&&(e=g._clip)}if(null===e)return null;e=new Td(this, -e,b);this._bindAction(e,g);this._addInactiveAction(e,c,d);return e},existingAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?Ha.findByName(c,a):a,c=this._actionsByClip[c?c.uuid:a];return void 0!==c?c.actionByRoot[d]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=0;return this},update:function(a){a*= -this.timeScale;for(var b=this._actions,c=this._nActiveActions,d=this.time+=a,e=Math.sign(a),f=this._accuIndex^=1,g=0;g!==c;++g){var h=b[g];h.enabled&&h._update(d,a,e,f)}a=this._bindings;b=this._nActiveBindings;for(g=0;g!==b;++g)a[g].apply(f);return this},getRoot:function(){return this._root},uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,d=c[a];if(void 0!==d){for(var d=d.knownActions,e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);var h=g._cacheIndex, -k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=this._bindingsByRootAndName[a];if(void 0!==c)for(var e in c)a=c[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){var c=this.existingAction(a,b); -null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Object.assign(Ud.prototype,{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings,g=a._interpolants,h=c.uuid,k=this._bindingsByRootAndName,l=k[h];void 0===l&&(l={},k[h]=l);for(k=0;k!==e;++k){var q=d[k],n=q.name,p=l[n];if(void 0===p){p=f[k];if(void 0!==p){null===p._cacheIndex&&(++p.referenceCount,this._addInactiveBinding(p,h,n));continue}p=new wd(fa.create(c,n,b&&b._propertyBindings[k].binding.parsedPath), -q.ValueTypeName,q.getValueSize());++p.referenceCount;this._addInactiveBinding(p,h,n)}f[k]=p;g[k].resultBuffer=p.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}}, -_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length}, -get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&ah.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c};na.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};na.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};na.prototype.setAnimationFPS=function(a,b){var c= -this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};na.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};na.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};na.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};na.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};na.prototype.getAnimationDuration= -function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};na.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};na.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};na.prototype.update=function(a){for(var b=0,c=this.animationsList.length;b -d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+T.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!== -d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};Qc.prototype=Object.create(z.prototype);Qc.prototype.constructor=Qc;Qc.prototype.isImmediateRenderObject=!0;Rc.prototype=Object.create(la.prototype);Rc.prototype.constructor=Rc;Rc.prototype.update=function(){var a=new q,b=new q,c=new Ia;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld); -var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,q=k.length;lc.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Cb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix(); -this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Cb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};xd.prototype=Object.create(la.prototype);xd.prototype.constructor=xd;var $d=function(){function a(){}var b=new q,c=new a,d=new a,e=new a;a.prototype.init=function(a,b,c,d){this.c0=a;this.c1=c;this.c2=-3*a+3*b-2*c-d;this.c3=2*a-2*b+c+d};a.prototype.initNonuniformCatmullRom=function(a,b,c,d,e,l,n){this.init(b,c,((b-a)/e-(c-a)/ -(e+l)+(c-b)/l)*l,((c-b)/l-(d-b)/(l+n)+(d-c)/n)*l)};a.prototype.initCatmullRom=function(a,b,c,d,e){this.init(b,c,e*(c-a),e*(d-b))};a.prototype.calc=function(a){var b=a*a;return this.c0+this.c1*a+this.c2*b+this.c3*b*a};return ia.create(function(a){this.points=a||[];this.closed=!1},function(a){var g=this.points,h,k;k=g.length;2>k&&console.log("duh, you need at least 2 points");a*=k-(this.closed?0:1);h=Math.floor(a);a-=h;this.closed?h+=0h&&(h=1);1E-4>k&&(k=h);1E-4>p&&(p=h);c.initNonuniformCatmullRom(l.x,w.x,n.x,g.x,k, -h,p);d.initNonuniformCatmullRom(l.y,w.y,n.y,g.y,k,h,p);e.initNonuniformCatmullRom(l.z,w.z,n.z,g.z,k,h,p)}else"catmullrom"===this.type&&(k=void 0!==this.tension?this.tension:.5,c.initCatmullRom(l.x,w.x,n.x,g.x,k),d.initCatmullRom(l.y,w.y,n.y,g.y,k),e.initCatmullRom(l.z,w.z,n.z,g.z,k));return new q(c.calc(a),d.calc(a),e.calc(a))})}();Ee.prototype=Object.create($d.prototype);var Ef=ia.create(function(a){console.warn("THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3");this.points= -void 0===a?[]:a},function(a){var b=this.points;a*=b.length-1;var c=Math.floor(a);a-=c;var d=b[0==c?c:c-1],e=b[c],f=b[c>b.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=Xc.interpolate;return new q(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a),c(d.z,e.z,f.z,b.z,a))}),Ff=ia.create(function(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d},function(a){var b=ra.b3;return new q(b(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y),b(a,this.v0.z,this.v1.z,this.v2.z, -this.v3.z))}),Gf=ia.create(function(a,b,c){this.v0=a;this.v1=b;this.v2=c},function(a){var b=ra.b2;return new q(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y),b(a,this.v0.z,this.v1.z,this.v2.z))}),Hf=ia.create(function(a,b){this.v1=a;this.v2=b},function(a){if(1===a)return this.v2.clone();var b=new q;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);b.add(this.v1);return b});yd.prototype=Object.create(Va.prototype);yd.prototype.constructor=yd;Object.assign(mc.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter()."); -return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(Ba.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter()."); -return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize()."); -return this.getSize(a)}});Object.assign(gb.prototype,{center:function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)}});Object.assign(Ia.prototype,{multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(a){console.warn("THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead."); -return this.applyToVector3Array(a)}});Object.assign(J.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead."); -return a.applyProjection(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector3Array:function(a){console.warn("THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");return this.applyToVector3Array(a)},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead."); -a.transformDirection(this)},crossVector:function(a){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},translate:function(a){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(a){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(a){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(a){console.error("THREE.Matrix4: .rotateZ() has been removed.")}, -rotateByAxis:function(a,b){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")}});Object.assign(va.prototype,{isIntersectionLine:function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)}});Object.assign(ba.prototype,{multiplyVector3:function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)}});Object.assign(ab.prototype, -{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(Ab.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead."); -return new za(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new cb(this,a)}});Object.assign(q.prototype,{setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")}, -getPositionFromMatrix:function(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(a)},getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b, -a)}});Object.assign(z.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");return this.getObjectByName(a)},renderDepth:function(a){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(z.prototype, -{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(a){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}}); -Object.defineProperties(rc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Ea.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(pa.prototype,{onlyShadow:{set:function(a){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov."); -this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom."); -this.shadow.camera.bottom=a}},shadowCameraNear:{set:function(a){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=a}},shadowCameraFar:{set:function(a){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far.");this.shadow.camera.far=a}},shadowCameraVisible:{set:function(a){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias."); -this.shadow.bias=a}},shadowDarkness:{set:function(a){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(a){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.");this.shadow.mapSize.width=a}},shadowMapHeight:{set:function(a){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=a}}});Object.defineProperties(C.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Please use .count."); -return this.array.length}}});Object.assign(G.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,b)},clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups()."); -this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}});Object.defineProperties(G.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");return this.groups}}}); -Object.defineProperties(U.prototype,{wrapAround:{get:function(){console.warn("THREE."+this.type+": .wrapAround has been removed.")},set:function(a){console.warn("THREE."+this.type+": .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE."+this.type+": .wrapRGB has been removed.");return new O}}});Object.defineProperties(db.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(a){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}}); -Object.defineProperties(Fa.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});sa.prototype=Object.assign(Object.create({constructor:sa,apply:function(a){console.warn("THREE.EventDispatcher: .apply is deprecated, just inherit or Object.assign the prototype to mix-in."); -Object.assign(a,this)}}),sa.prototype);Object.defineProperties(Ae.prototype,{dynamic:{set:function(a){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");return this}}});Object.assign(Dd.prototype,{supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' )."); -return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' )."); -return this.extensions.get("WEBGL_compressed_texture_s3tc")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){return this.capabilities.vertexTextures}, -supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")}, -addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Dd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type."); -this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");this.shadowMap.cullFace=a}}});Object.defineProperties(pe.prototype,{cullFace:{get:function(){return this.renderReverseSided?2:1},set:function(a){a=1!==a;console.warn("WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to "+a+".");this.renderReverseSided=a}}});Object.defineProperties(Db.prototype, -{wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."); -return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."); -return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat}, -set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."); -this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});Object.assign(dc.prototype,{load:function(a){console.warn("THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.");var b=this;(new Od).load(a,function(a){b.setBuffer(a)}); -return this}});Object.assign(Rd.prototype,{getData:function(a){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()}});l.WebGLRenderTargetCube=Eb;l.WebGLRenderTarget=Db;l.WebGLRenderer=Dd;l.ShaderLib=Gb;l.UniformsLib=W;l.UniformsUtils=La;l.ShaderChunk=X;l.FogExp2=Ib;l.Fog=Jb;l.Scene=jb;l.LensFlare=Ed;l.Sprite=qc;l.LOD=rc;l.SkinnedMesh=dd;l.Skeleton=bd;l.Bone=cd;l.Mesh=ya;l.LineSegments=la;l.Line=Ta;l.Points=Kb;l.Group=sc;l.VideoTexture=ed;l.DataTexture= -lb;l.CompressedTexture=Lb;l.CubeTexture=Xa;l.CanvasTexture=fd;l.DepthTexture=tc;l.TextureIdCount=function(){return ee++};l.Texture=da;l.MaterialIdCount=function(){return oe++};l.CompressedTextureLoader=we;l.BinaryTextureLoader=Gd;l.DataTextureLoader=Gd;l.CubeTextureLoader=Hd;l.TextureLoader=gd;l.ObjectLoader=xe;l.MaterialLoader=ud;l.BufferGeometryLoader=Id;l.DefaultLoadingManager=Ga;l.LoadingManager=Fd;l.JSONLoader=Jd;l.ImageLoader=Lc;l.FontLoader=ye;l.XHRLoader=Ja;l.Loader=wb;l.Cache=ce;l.AudioLoader= -Od;l.SpotLightShadow=id;l.SpotLight=jd;l.PointLight=kd;l.HemisphereLight=hd;l.DirectionalLightShadow=ld;l.DirectionalLight=md;l.AmbientLight=nd;l.LightShadow=tb;l.Light=pa;l.StereoCamera=ze;l.PerspectiveCamera=Ea;l.OrthographicCamera=Hb;l.CubeCamera=vd;l.Camera=Z;l.AudioListener=Pd;l.PositionalAudio=Qd;l.getAudioContext=Md;l.AudioAnalyser=Rd;l.Audio=dc;l.VectorKeyframeTrack=bc;l.StringKeyframeTrack=rd;l.QuaternionKeyframeTrack=Nc;l.NumberKeyframeTrack=cc;l.ColorKeyframeTrack=td;l.BooleanKeyframeTrack= -sd;l.PropertyMixer=wd;l.PropertyBinding=fa;l.KeyframeTrack=vb;l.AnimationUtils=ma;l.AnimationObjectGroup=Sd;l.AnimationMixer=Ud;l.AnimationClip=Ha;l.Uniform=Ae;l.InstancedBufferGeometry=Bb;l.BufferGeometry=G;l.GeometryIdCount=function(){return ad++};l.Geometry=Q;l.InterleavedBufferAttribute=Vd;l.InstancedInterleavedBuffer=fc;l.InterleavedBuffer=ec;l.InstancedBufferAttribute=gc;l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead."); -return(new C(a,b)).setDynamic(!0)};l.Float64Attribute=function(a,b){return new C(new Float64Array(a),b)};l.Float32Attribute=ha;l.Uint32Attribute=$c;l.Int32Attribute=function(a,b){return new C(new Int32Array(a),b)};l.Uint16Attribute=Zc;l.Int16Attribute=function(a,b){return new C(new Int16Array(a),b)};l.Uint8ClampedAttribute=function(a,b){return new C(new Uint8ClampedArray(a),b)};l.Uint8Attribute=function(a,b){return new C(new Uint8Array(a),b)};l.Int8Attribute=function(a,b){return new C(new Int8Array(a), -b)};l.BufferAttribute=C;l.Face3=ea;l.Object3DIdCount=function(){return qe++};l.Object3D=z;l.Raycaster=Wd;l.Layers=Yc;l.EventDispatcher=sa;l.Clock=Yd;l.QuaternionLinearInterpolant=qd;l.LinearInterpolant=Mc;l.DiscreteInterpolant=pd;l.CubicInterpolant=od;l.Interpolant=qa;l.Triangle=wa;l.Spline=function(a){function b(a,b,c,d,e,f,g){a=.5*(c-a);d=.5*(d-b);return(2*(b-c)+a+d)*g+(-3*(b-c)-2*a-d)*f+a*e+b}this.points=a;var c=[],d={x:0,y:0,z:0},e,f,g,h,k,l,w,n,p;this.initFromArray=function(a){this.points=[]; -for(var b=0;bthis.points.length-2?this.points.length-1:f+1;c[3]=f>this.points.length-3?this.points.length-1:f+2;l=this.points[c[0]];w=this.points[c[1]];n=this.points[c[2]];p=this.points[c[3]];h=g*g;k=g*h;d.x=b(l.x,w.x,n.x,p.x,g,h,k);d.y=b(l.y,w.y,n.y,p.y,g,h,k);d.z=b(l.z,w.z,n.z,p.z,g,h,k);return d};this.getControlPointsArray=function(){var a, -b,c=this.points.length,d=[];for(a=0;aFlattens an Observable-of-Observables by putting one + * inner Observable after the other. + * + * + * + * Joins every Observable emitted by the source (a higher-order Observable), in + * a serial fashion. It subscribes to each inner Observable only after the + * previous inner Observable has completed, and merges all of their values into + * the returned observable. + * + * __Warning:__ If the source Observable emits Observables quickly and + * endlessly, and the inner Observables it emits generally complete slower than + * the source emits, you can run into memory issues as the incoming Observables + * collect in an unbounded buffer. + * + * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set + * to `1`. + * + * @example For each click event, tick every second from 0 to 3, with no concurrency + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var higherOrder = clicks.map(ev => Rx.Observable.interval(1000).take(4)); + * var firstOrder = higherOrder.concatAll(); + * firstOrder.subscribe(x => console.log(x)); + * + * // Results in the following: + * // (results are not concurrent) + * // For every click on the "document" it will emit values 0 to 3 spaced + * // on a 1000ms interval + * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 + * + * @see {@link combineAll} + * @see {@link concat} + * @see {@link concatMap} + * @see {@link concatMapTo} + * @see {@link exhaust} + * @see {@link mergeAll} + * @see {@link switch} + * @see {@link zipAll} + * + * @return {Observable} An Observable emitting values from all the inner + * Observables concatenated. + * @method concatAll + * @owner Observable + */ +function concatAll() { + return mergeAll_1.mergeAll(1); +} +exports.concatAll = concatAll; - // Export the Underscore object for **Node.js**, with - // backwards-compatibility for the old `require()` API. If we're in - // the browser, add `_` as a global object. - if (typeof exports !== 'undefined') { - if (typeof module !== 'undefined' && module.exports) { - exports = module.exports = _; +},{"./mergeAll":180}],167:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/** + * Counts the number of emissions on the source and emits that number when the + * source completes. + * + * Tells how many values were emitted, when the source + * completes. + * + * + * + * `count` transforms an Observable that emits values into an Observable that + * emits a single value that represents the number of values emitted by the + * source Observable. If the source Observable terminates with an error, `count` + * will pass this error notification along without emitting a value first. If + * the source Observable does not terminate at all, `count` will neither emit + * a value nor terminate. This operator takes an optional `predicate` function + * as argument, in which case the output emission will represent the number of + * source values that matched `true` with the `predicate`. + * + * @example Counts how many seconds have passed before the first click happened + * var seconds = Rx.Observable.interval(1000); + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var secondsBeforeClick = seconds.takeUntil(clicks); + * var result = secondsBeforeClick.count(); + * result.subscribe(x => console.log(x)); + * + * @example Counts how many odd numbers are there between 1 and 7 + * var numbers = Rx.Observable.range(1, 7); + * var result = numbers.count(i => i % 2 === 1); + * result.subscribe(x => console.log(x)); + * + * // Results in: + * // 4 + * + * @see {@link max} + * @see {@link min} + * @see {@link reduce} + * + * @param {function(value: T, i: number, source: Observable): boolean} [predicate] A + * boolean function to select what values are to be counted. It is provided with + * arguments of: + * - `value`: the value from the source Observable. + * - `index`: the (zero-based) "index" of the value from the source Observable. + * - `source`: the source Observable instance itself. + * @return {Observable} An Observable of one number that represents the count as + * described above. + * @method count + * @owner Observable + */ +function count(predicate) { + return function (source) { return source.lift(new CountOperator(predicate, source)); }; +} +exports.count = count; +var CountOperator = (function () { + function CountOperator(predicate, source) { + this.predicate = predicate; + this.source = source; } - exports._ = _; - } else { - root._ = _; - } - - // Current version. - _.VERSION = '1.8.3'; - - // Internal function that returns an efficient (for current engines) version - // of the passed-in callback, to be repeatedly applied in other Underscore - // functions. - var optimizeCb = function(func, context, argCount) { - if (context === void 0) return func; - switch (argCount == null ? 3 : argCount) { - case 1: return function(value) { - return func.call(context, value); - }; - case 2: return function(value, other) { - return func.call(context, value, other); - }; - case 3: return function(value, index, collection) { - return func.call(context, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(context, accumulator, value, index, collection); - }; + CountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source)); + }; + return CountOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var CountSubscriber = (function (_super) { + __extends(CountSubscriber, _super); + function CountSubscriber(destination, predicate, source) { + _super.call(this, destination); + this.predicate = predicate; + this.source = source; + this.count = 0; + this.index = 0; } - return function() { - return func.apply(context, arguments); + CountSubscriber.prototype._next = function (value) { + if (this.predicate) { + this._tryPredicate(value); + } + else { + this.count++; + } }; - }; - - // A mostly-internal function to generate callbacks that can be applied - // to each element in a collection, returning the desired result — either - // identity, an arbitrary callback, a property matcher, or a property accessor. - var cb = function(value, context, argCount) { - if (value == null) return _.identity; - if (_.isFunction(value)) return optimizeCb(value, context, argCount); - if (_.isObject(value)) return _.matcher(value); - return _.property(value); - }; - _.iteratee = function(value, context) { - return cb(value, context, Infinity); - }; - - // An internal function for creating assigner functions. - var createAssigner = function(keysFunc, undefinedOnly) { - return function(obj) { - var length = arguments.length; - if (length < 2 || obj == null) return obj; - for (var index = 1; index < length; index++) { - var source = arguments[index], - keys = keysFunc(source), - l = keys.length; - for (var i = 0; i < l; i++) { - var key = keys[i]; - if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + CountSubscriber.prototype._tryPredicate = function (value) { + var result; + try { + result = this.predicate(value, this.index++, this.source); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + this.count++; } - } - return obj; }; - }; - - // An internal function for creating a new object that inherits from another. - var baseCreate = function(prototype) { - if (!_.isObject(prototype)) return {}; - if (nativeCreate) return nativeCreate(prototype); - Ctor.prototype = prototype; - var result = new Ctor; - Ctor.prototype = null; - return result; - }; - - var property = function(key) { - return function(obj) { - return obj == null ? void 0 : obj[key]; + CountSubscriber.prototype._complete = function () { + this.destination.next(this.count); + this.destination.complete(); }; - }; - - // Helper for collection methods to determine whether a collection - // should be iterated as an array or as an object - // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength - // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 - var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; - var getLength = property('length'); - var isArrayLike = function(collection) { - var length = getLength(collection); - return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; - }; - - // Collection Functions - // -------------------- - - // The cornerstone, an `each` implementation, aka `forEach`. - // Handles raw objects in addition to array-likes. Treats all - // sparse array-likes as if they were dense. - _.each = _.forEach = function(obj, iteratee, context) { - iteratee = optimizeCb(iteratee, context); - var i, length; - if (isArrayLike(obj)) { - for (i = 0, length = obj.length; i < length; i++) { - iteratee(obj[i], i, obj); - } - } else { - var keys = _.keys(obj); - for (i = 0, length = keys.length; i < length; i++) { - iteratee(obj[keys[i]], keys[i], obj); - } - } - return obj; - }; + return CountSubscriber; +}(Subscriber_1.Subscriber)); - // Return the results of applying the iteratee to each element. - _.map = _.collect = function(obj, iteratee, context) { - iteratee = cb(iteratee, context); - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length, - results = Array(length); - for (var index = 0; index < length; index++) { - var currentKey = keys ? keys[index] : index; - results[index] = iteratee(obj[currentKey], currentKey, obj); +},{"../Subscriber":36}],168:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var async_1 = require('../scheduler/async'); +/** + * Emits a value from the source Observable only after a particular time span + * has passed without another source emission. + * + * It's like {@link delay}, but passes only the most + * recent value from each burst of emissions. + * + * + * + * `debounceTime` delays values emitted by the source Observable, but drops + * previous pending delayed emissions if a new value arrives on the source + * Observable. This operator keeps track of the most recent value from the + * source Observable, and emits that only when `dueTime` enough time has passed + * without any other value appearing on the source Observable. If a new value + * appears before `dueTime` silence occurs, the previous value will be dropped + * and will not be emitted on the output Observable. + * + * This is a rate-limiting operator, because it is impossible for more than one + * value to be emitted in any time window of duration `dueTime`, but it is also + * a delay-like operator since output emissions do not occur at the same time as + * they did on the source Observable. Optionally takes a {@link IScheduler} for + * managing timers. + * + * @example Emit the most recent click after a burst of clicks + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.debounceTime(1000); + * result.subscribe(x => console.log(x)); + * + * @see {@link auditTime} + * @see {@link debounce} + * @see {@link delay} + * @see {@link sampleTime} + * @see {@link throttleTime} + * + * @param {number} dueTime The timeout duration in milliseconds (or the time + * unit determined internally by the optional `scheduler`) for the window of + * time required to wait for emission silence before emitting the most recent + * source value. + * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for + * managing the timers that handle the timeout for each value. + * @return {Observable} An Observable that delays the emissions of the source + * Observable by the specified `dueTime`, and may drop some values if they occur + * too frequently. + * @method debounceTime + * @owner Observable + */ +function debounceTime(dueTime, scheduler) { + if (scheduler === void 0) { scheduler = async_1.async; } + return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); }; +} +exports.debounceTime = debounceTime; +var DebounceTimeOperator = (function () { + function DebounceTimeOperator(dueTime, scheduler) { + this.dueTime = dueTime; + this.scheduler = scheduler; } - return results; - }; - - // Create a reducing function iterating left or right. - function createReduce(dir) { - // Optimized iterator function as using arguments.length - // in the main function will deoptimize the, see #1991. - function iterator(obj, iteratee, memo, keys, index, length) { - for (; index >= 0 && index < length; index += dir) { - var currentKey = keys ? keys[index] : index; - memo = iteratee(memo, obj[currentKey], currentKey, obj); - } - return memo; + DebounceTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler)); + }; + return DebounceTimeOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var DebounceTimeSubscriber = (function (_super) { + __extends(DebounceTimeSubscriber, _super); + function DebounceTimeSubscriber(destination, dueTime, scheduler) { + _super.call(this, destination); + this.dueTime = dueTime; + this.scheduler = scheduler; + this.debouncedSubscription = null; + this.lastValue = null; + this.hasValue = false; } - - return function(obj, iteratee, memo, context) { - iteratee = optimizeCb(iteratee, context, 4); - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length, - index = dir > 0 ? 0 : length - 1; - // Determine the initial value if none is provided. - if (arguments.length < 3) { - memo = obj[keys ? keys[index] : index]; - index += dir; - } - return iterator(obj, iteratee, memo, keys, index, length); + DebounceTimeSubscriber.prototype._next = function (value) { + this.clearDebounce(); + this.lastValue = value; + this.hasValue = true; + this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this)); }; - } - - // **Reduce** builds up a single result from a list of values, aka `inject`, - // or `foldl`. - _.reduce = _.foldl = _.inject = createReduce(1); - - // The right-associative version of reduce, also known as `foldr`. - _.reduceRight = _.foldr = createReduce(-1); + DebounceTimeSubscriber.prototype._complete = function () { + this.debouncedNext(); + this.destination.complete(); + }; + DebounceTimeSubscriber.prototype.debouncedNext = function () { + this.clearDebounce(); + if (this.hasValue) { + this.destination.next(this.lastValue); + this.lastValue = null; + this.hasValue = false; + } + }; + DebounceTimeSubscriber.prototype.clearDebounce = function () { + var debouncedSubscription = this.debouncedSubscription; + if (debouncedSubscription !== null) { + this.remove(debouncedSubscription); + debouncedSubscription.unsubscribe(); + this.debouncedSubscription = null; + } + }; + return DebounceTimeSubscriber; +}(Subscriber_1.Subscriber)); +function dispatchNext(subscriber) { + subscriber.debouncedNext(); +} - // Return the first value which passes a truth test. Aliased as `detect`. - _.find = _.detect = function(obj, predicate, context) { - var key; - if (isArrayLike(obj)) { - key = _.findIndex(obj, predicate, context); - } else { - key = _.findKey(obj, predicate, context); +},{"../Subscriber":36,"../scheduler/async":212}],169:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/* tslint:enable:max-line-length */ +/** + * Emits a given value if the source Observable completes without emitting any + * `next` value, otherwise mirrors the source Observable. + * + * If the source Observable turns out to be empty, then + * this operator will emit a default value. + * + * + * + * `defaultIfEmpty` emits the values emitted by the source Observable or a + * specified default value if the source Observable is empty (completes without + * having emitted any `next` value). + * + * @example If no clicks happen in 5 seconds, then emit "no clicks" + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var clicksBeforeFive = clicks.takeUntil(Rx.Observable.interval(5000)); + * var result = clicksBeforeFive.defaultIfEmpty('no clicks'); + * result.subscribe(x => console.log(x)); + * + * @see {@link empty} + * @see {@link last} + * + * @param {any} [defaultValue=null] The default value used if the source + * Observable is empty. + * @return {Observable} An Observable that emits either the specified + * `defaultValue` if the source Observable emits no items, or the values emitted + * by the source Observable. + * @method defaultIfEmpty + * @owner Observable + */ +function defaultIfEmpty(defaultValue) { + if (defaultValue === void 0) { defaultValue = null; } + return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); }; +} +exports.defaultIfEmpty = defaultIfEmpty; +var DefaultIfEmptyOperator = (function () { + function DefaultIfEmptyOperator(defaultValue) { + this.defaultValue = defaultValue; } - if (key !== void 0 && key !== -1) return obj[key]; - }; - - // Return all the elements that pass a truth test. - // Aliased as `select`. - _.filter = _.select = function(obj, predicate, context) { - var results = []; - predicate = cb(predicate, context); - _.each(obj, function(value, index, list) { - if (predicate(value, index, list)) results.push(value); - }); - return results; - }; - - // Return all the elements for which a truth test fails. - _.reject = function(obj, predicate, context) { - return _.filter(obj, _.negate(cb(predicate)), context); - }; - - // Determine whether all of the elements match a truth test. - // Aliased as `all`. - _.every = _.all = function(obj, predicate, context) { - predicate = cb(predicate, context); - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = keys ? keys[index] : index; - if (!predicate(obj[currentKey], currentKey, obj)) return false; + DefaultIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue)); + }; + return DefaultIfEmptyOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var DefaultIfEmptySubscriber = (function (_super) { + __extends(DefaultIfEmptySubscriber, _super); + function DefaultIfEmptySubscriber(destination, defaultValue) { + _super.call(this, destination); + this.defaultValue = defaultValue; + this.isEmpty = true; } - return true; - }; + DefaultIfEmptySubscriber.prototype._next = function (value) { + this.isEmpty = false; + this.destination.next(value); + }; + DefaultIfEmptySubscriber.prototype._complete = function () { + if (this.isEmpty) { + this.destination.next(this.defaultValue); + } + this.destination.complete(); + }; + return DefaultIfEmptySubscriber; +}(Subscriber_1.Subscriber)); - // Determine if at least one element in the object matches a truth test. - // Aliased as `any`. - _.some = _.any = function(obj, predicate, context) { - predicate = cb(predicate, context); - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = keys ? keys[index] : index; - if (predicate(obj[currentKey], currentKey, obj)) return true; +},{"../Subscriber":36}],170:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var async_1 = require('../scheduler/async'); +var isDate_1 = require('../util/isDate'); +var Subscriber_1 = require('../Subscriber'); +var Notification_1 = require('../Notification'); +/** + * Delays the emission of items from the source Observable by a given timeout or + * until a given Date. + * + * Time shifts each item by some specified amount of + * milliseconds. + * + * + * + * If the delay argument is a Number, this operator time shifts the source + * Observable by that amount of time expressed in milliseconds. The relative + * time intervals between the values are preserved. + * + * If the delay argument is a Date, this operator time shifts the start of the + * Observable execution until the given date occurs. + * + * @example Delay each click by one second + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second + * delayedClicks.subscribe(x => console.log(x)); + * + * @example Delay all clicks until a future date happens + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var date = new Date('March 15, 2050 12:00:00'); // in the future + * var delayedClicks = clicks.delay(date); // click emitted only after that date + * delayedClicks.subscribe(x => console.log(x)); + * + * @see {@link debounceTime} + * @see {@link delayWhen} + * + * @param {number|Date} delay The delay duration in milliseconds (a `number`) or + * a `Date` until which the emission of the source items is delayed. + * @param {Scheduler} [scheduler=async] The IScheduler to use for + * managing the timers that handle the time-shift for each item. + * @return {Observable} An Observable that delays the emissions of the source + * Observable by the specified timeout or Date. + * @method delay + * @owner Observable + */ +function delay(delay, scheduler) { + if (scheduler === void 0) { scheduler = async_1.async; } + var absoluteDelay = isDate_1.isDate(delay); + var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); + return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); }; +} +exports.delay = delay; +var DelayOperator = (function () { + function DelayOperator(delay, scheduler) { + this.delay = delay; + this.scheduler = scheduler; } - return false; - }; - - // Determine if the array or object contains a given item (using `===`). - // Aliased as `includes` and `include`. - _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { - if (!isArrayLike(obj)) obj = _.values(obj); - if (typeof fromIndex != 'number' || guard) fromIndex = 0; - return _.indexOf(obj, item, fromIndex) >= 0; - }; - - // Invoke a method (with arguments) on every item in a collection. - _.invoke = function(obj, method) { - var args = slice.call(arguments, 2); - var isFunc = _.isFunction(method); - return _.map(obj, function(value) { - var func = isFunc ? method : value[method]; - return func == null ? func : func.apply(value, args); - }); - }; - - // Convenience version of a common use case of `map`: fetching a property. - _.pluck = function(obj, key) { - return _.map(obj, _.property(key)); - }; - - // Convenience version of a common use case of `filter`: selecting only objects - // containing specific `key:value` pairs. - _.where = function(obj, attrs) { - return _.filter(obj, _.matcher(attrs)); - }; - - // Convenience version of a common use case of `find`: getting the first object - // containing specific `key:value` pairs. - _.findWhere = function(obj, attrs) { - return _.find(obj, _.matcher(attrs)); - }; - - // Return the maximum element (or element-based computation). - _.max = function(obj, iteratee, context) { - var result = -Infinity, lastComputed = -Infinity, - value, computed; - if (iteratee == null && obj != null) { - obj = isArrayLike(obj) ? obj : _.values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value > result) { - result = value; + DelayOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler)); + }; + return DelayOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var DelaySubscriber = (function (_super) { + __extends(DelaySubscriber, _super); + function DelaySubscriber(destination, delay, scheduler) { + _super.call(this, destination); + this.delay = delay; + this.scheduler = scheduler; + this.queue = []; + this.active = false; + this.errored = false; + } + DelaySubscriber.dispatch = function (state) { + var source = state.source; + var queue = source.queue; + var scheduler = state.scheduler; + var destination = state.destination; + while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) { + queue.shift().notification.observe(destination); } - } - } else { - iteratee = cb(iteratee, context); - _.each(obj, function(value, index, list) { - computed = iteratee(value, index, list); - if (computed > lastComputed || computed === -Infinity && result === -Infinity) { - result = value; - lastComputed = computed; + if (queue.length > 0) { + var delay_1 = Math.max(0, queue[0].time - scheduler.now()); + this.schedule(state, delay_1); } - }); - } - return result; - }; - - // Return the minimum element (or element-based computation). - _.min = function(obj, iteratee, context) { - var result = Infinity, lastComputed = Infinity, - value, computed; - if (iteratee == null && obj != null) { - obj = isArrayLike(obj) ? obj : _.values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value < result) { - result = value; + else { + source.active = false; } - } - } else { - iteratee = cb(iteratee, context); - _.each(obj, function(value, index, list) { - computed = iteratee(value, index, list); - if (computed < lastComputed || computed === Infinity && result === Infinity) { - result = value; - lastComputed = computed; + }; + DelaySubscriber.prototype._schedule = function (scheduler) { + this.active = true; + this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, { + source: this, destination: this.destination, scheduler: scheduler + })); + }; + DelaySubscriber.prototype.scheduleNotification = function (notification) { + if (this.errored === true) { + return; } - }); + var scheduler = this.scheduler; + var message = new DelayMessage(scheduler.now() + this.delay, notification); + this.queue.push(message); + if (this.active === false) { + this._schedule(scheduler); + } + }; + DelaySubscriber.prototype._next = function (value) { + this.scheduleNotification(Notification_1.Notification.createNext(value)); + }; + DelaySubscriber.prototype._error = function (err) { + this.errored = true; + this.queue = []; + this.destination.error(err); + }; + DelaySubscriber.prototype._complete = function () { + this.scheduleNotification(Notification_1.Notification.createComplete()); + }; + return DelaySubscriber; +}(Subscriber_1.Subscriber)); +var DelayMessage = (function () { + function DelayMessage(time, notification) { + this.time = time; + this.notification = notification; } - return result; - }; + return DelayMessage; +}()); - // Shuffle a collection, using the modern version of the - // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). - _.shuffle = function(obj) { - var set = isArrayLike(obj) ? obj : _.values(obj); - var length = set.length; - var shuffled = Array(length); - for (var index = 0, rand; index < length; index++) { - rand = _.random(0, index); - if (rand !== index) shuffled[index] = shuffled[rand]; - shuffled[rand] = set[index]; +},{"../Notification":28,"../Subscriber":36,"../scheduler/async":212,"../util/isDate":228}],171:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +var Set_1 = require('../util/Set'); +/** + * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items. + * + * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will + * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the + * source observable directly with an equality check against previous values. + * + * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking. + * + * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the + * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct` + * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so + * that the internal `Set` can be "flushed", basically clearing it of values. + * + * @example A simple example with numbers + * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1) + * .distinct() + * .subscribe(x => console.log(x)); // 1, 2, 3, 4 + * + * @example An example using a keySelector function + * interface Person { + * age: number, + * name: string + * } + * + * Observable.of( + * { age: 4, name: 'Foo'}, + * { age: 7, name: 'Bar'}, + * { age: 5, name: 'Foo'}) + * .distinct((p: Person) => p.name) + * .subscribe(x => console.log(x)); + * + * // displays: + * // { age: 4, name: 'Foo' } + * // { age: 7, name: 'Bar' } + * + * @see {@link distinctUntilChanged} + * @see {@link distinctUntilKeyChanged} + * + * @param {function} [keySelector] Optional function to select which value you want to check as distinct. + * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator. + * @return {Observable} An Observable that emits items from the source Observable with distinct values. + * @method distinct + * @owner Observable + */ +function distinct(keySelector, flushes) { + return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); }; +} +exports.distinct = distinct; +var DistinctOperator = (function () { + function DistinctOperator(keySelector, flushes) { + this.keySelector = keySelector; + this.flushes = flushes; } - return shuffled; - }; - - // Sample **n** random values from a collection. - // If **n** is not specified, returns a single random element. - // The internal `guard` argument allows it to work with `map`. - _.sample = function(obj, n, guard) { - if (n == null || guard) { - if (!isArrayLike(obj)) obj = _.values(obj); - return obj[_.random(obj.length - 1)]; + DistinctOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes)); + }; + return DistinctOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var DistinctSubscriber = (function (_super) { + __extends(DistinctSubscriber, _super); + function DistinctSubscriber(destination, keySelector, flushes) { + _super.call(this, destination); + this.keySelector = keySelector; + this.values = new Set_1.Set(); + if (flushes) { + this.add(subscribeToResult_1.subscribeToResult(this, flushes)); + } } - return _.shuffle(obj).slice(0, Math.max(0, n)); - }; - - // Sort the object's values by a criterion produced by an iteratee. - _.sortBy = function(obj, iteratee, context) { - iteratee = cb(iteratee, context); - return _.pluck(_.map(obj, function(value, index, list) { - return { - value: value, - index: index, - criteria: iteratee(value, index, list) - }; - }).sort(function(left, right) { - var a = left.criteria; - var b = right.criteria; - if (a !== b) { - if (a > b || a === void 0) return 1; - if (a < b || b === void 0) return -1; - } - return left.index - right.index; - }), 'value'); - }; - - // An internal function used for aggregate "group by" operations. - var group = function(behavior) { - return function(obj, iteratee, context) { - var result = {}; - iteratee = cb(iteratee, context); - _.each(obj, function(value, index) { - var key = iteratee(value, index, obj); - behavior(result, value, key); - }); - return result; + DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.values.clear(); }; - }; - - // Groups the object's values by a criterion. Pass either a string attribute - // to group by, or a function that returns the criterion. - _.groupBy = group(function(result, value, key) { - if (_.has(result, key)) result[key].push(value); else result[key] = [value]; - }); - - // Indexes the object's values by a criterion, similar to `groupBy`, but for - // when you know that your index values will be unique. - _.indexBy = group(function(result, value, key) { - result[key] = value; - }); - - // Counts instances of an object that group by a certain criterion. Pass - // either a string attribute to count by, or a function that returns the - // criterion. - _.countBy = group(function(result, value, key) { - if (_.has(result, key)) result[key]++; else result[key] = 1; - }); + DistinctSubscriber.prototype.notifyError = function (error, innerSub) { + this._error(error); + }; + DistinctSubscriber.prototype._next = function (value) { + if (this.keySelector) { + this._useKeySelector(value); + } + else { + this._finalizeNext(value, value); + } + }; + DistinctSubscriber.prototype._useKeySelector = function (value) { + var key; + var destination = this.destination; + try { + key = this.keySelector(value); + } + catch (err) { + destination.error(err); + return; + } + this._finalizeNext(key, value); + }; + DistinctSubscriber.prototype._finalizeNext = function (key, value) { + var values = this.values; + if (!values.has(key)) { + values.add(key); + this.destination.next(value); + } + }; + return DistinctSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); +exports.DistinctSubscriber = DistinctSubscriber; - // Safely create a real, live array from anything iterable. - _.toArray = function(obj) { - if (!obj) return []; - if (_.isArray(obj)) return slice.call(obj); +},{"../OuterSubscriber":31,"../util/Set":221,"../util/subscribeToResult":237}],172:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var tryCatch_1 = require('../util/tryCatch'); +var errorObject_1 = require('../util/errorObject'); +/* tslint:enable:max-line-length */ +/** + * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item. + * + * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted. + * + * If a comparator function is not provided, an equality check is used by default. + * + * @example A simple example with numbers + * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4) + * .distinctUntilChanged() + * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4 + * + * @example An example using a compare function + * interface Person { + * age: number, + * name: string + * } + * + * Observable.of( + * { age: 4, name: 'Foo'}, + * { age: 7, name: 'Bar'}, + * { age: 5, name: 'Foo'}) + * { age: 6, name: 'Foo'}) + * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name) + * .subscribe(x => console.log(x)); + * + * // displays: + * // { age: 4, name: 'Foo' } + * // { age: 7, name: 'Bar' } + * // { age: 5, name: 'Foo' } + * + * @see {@link distinct} + * @see {@link distinctUntilKeyChanged} + * + * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source. + * @return {Observable} An Observable that emits items from the source Observable with distinct values. + * @method distinctUntilChanged + * @owner Observable + */ +function distinctUntilChanged(compare, keySelector) { + return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); }; +} +exports.distinctUntilChanged = distinctUntilChanged; +var DistinctUntilChangedOperator = (function () { + function DistinctUntilChangedOperator(compare, keySelector) { + this.compare = compare; + this.keySelector = keySelector; + } + DistinctUntilChangedOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector)); + }; + return DistinctUntilChangedOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var DistinctUntilChangedSubscriber = (function (_super) { + __extends(DistinctUntilChangedSubscriber, _super); + function DistinctUntilChangedSubscriber(destination, compare, keySelector) { + _super.call(this, destination); + this.keySelector = keySelector; + this.hasKey = false; + if (typeof compare === 'function') { + this.compare = compare; + } + } + DistinctUntilChangedSubscriber.prototype.compare = function (x, y) { + return x === y; + }; + DistinctUntilChangedSubscriber.prototype._next = function (value) { + var keySelector = this.keySelector; + var key = value; + if (keySelector) { + key = tryCatch_1.tryCatch(this.keySelector)(value); + if (key === errorObject_1.errorObject) { + return this.destination.error(errorObject_1.errorObject.e); + } + } + var result = false; + if (this.hasKey) { + result = tryCatch_1.tryCatch(this.compare)(this.key, key); + if (result === errorObject_1.errorObject) { + return this.destination.error(errorObject_1.errorObject.e); + } + } + else { + this.hasKey = true; + } + if (Boolean(result) === false) { + this.key = key; + this.destination.next(value); + } + }; + return DistinctUntilChangedSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36,"../util/errorObject":224,"../util/tryCatch":239}],173:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var tryCatch_1 = require('../util/tryCatch'); +var errorObject_1 = require('../util/errorObject'); +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/* tslint:enable:max-line-length */ +/** + * Recursively projects each source value to an Observable which is merged in + * the output Observable. + * + * It's similar to {@link mergeMap}, but applies the + * projection function to every source value as well as every output value. + * It's recursive. + * + * + * + * Returns an Observable that emits items based on applying a function that you + * supply to each item emitted by the source Observable, where that function + * returns an Observable, and then merging those resulting Observables and + * emitting the results of this merger. *Expand* will re-emit on the output + * Observable every source value. Then, each output value is given to the + * `project` function which returns an inner Observable to be merged on the + * output Observable. Those output values resulting from the projection are also + * given to the `project` function to produce new output values. This is how + * *expand* behaves recursively. + * + * @example Start emitting the powers of two on every click, at most 10 of them + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var powersOfTwo = clicks + * .mapTo(1) + * .expand(x => Rx.Observable.of(2 * x).delay(1000)) + * .take(10); + * powersOfTwo.subscribe(x => console.log(x)); + * + * @see {@link mergeMap} + * @see {@link mergeScan} + * + * @param {function(value: T, index: number) => Observable} project A function + * that, when applied to an item emitted by the source or the output Observable, + * returns an Observable. + * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input + * Observables being subscribed to concurrently. + * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to + * each projected inner Observable. + * @return {Observable} An Observable that emits the source values and also + * result of applying the projection function to each value emitted on the + * output Observable and and merging the results of the Observables obtained + * from this transformation. + * @method expand + * @owner Observable + */ +function expand(project, concurrent, scheduler) { + if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } + if (scheduler === void 0) { scheduler = undefined; } + concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent; + return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); }; +} +exports.expand = expand; +var ExpandOperator = (function () { + function ExpandOperator(project, concurrent, scheduler) { + this.project = project; + this.concurrent = concurrent; + this.scheduler = scheduler; + } + ExpandOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler)); + }; + return ExpandOperator; +}()); +exports.ExpandOperator = ExpandOperator; +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var ExpandSubscriber = (function (_super) { + __extends(ExpandSubscriber, _super); + function ExpandSubscriber(destination, project, concurrent, scheduler) { + _super.call(this, destination); + this.project = project; + this.concurrent = concurrent; + this.scheduler = scheduler; + this.index = 0; + this.active = 0; + this.hasCompleted = false; + if (concurrent < Number.POSITIVE_INFINITY) { + this.buffer = []; + } + } + ExpandSubscriber.dispatch = function (arg) { + var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index; + subscriber.subscribeToProjection(result, value, index); + }; + ExpandSubscriber.prototype._next = function (value) { + var destination = this.destination; + if (destination.closed) { + this._complete(); + return; + } + var index = this.index++; + if (this.active < this.concurrent) { + destination.next(value); + var result = tryCatch_1.tryCatch(this.project)(value, index); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } + else if (!this.scheduler) { + this.subscribeToProjection(result, value, index); + } + else { + var state = { subscriber: this, result: result, value: value, index: index }; + this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state)); + } + } + else { + this.buffer.push(value); + } + }; + ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) { + this.active++; + this.add(subscribeToResult_1.subscribeToResult(this, result, value, index)); + }; + ExpandSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + }; + ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this._next(innerValue); + }; + ExpandSubscriber.prototype.notifyComplete = function (innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer && buffer.length > 0) { + this._next(buffer.shift()); + } + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + }; + return ExpandSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); +exports.ExpandSubscriber = ExpandSubscriber; + +},{"../OuterSubscriber":31,"../util/errorObject":224,"../util/subscribeToResult":237,"../util/tryCatch":239}],174:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/* tslint:enable:max-line-length */ +/** + * Filter items emitted by the source Observable by only emitting those that + * satisfy a specified predicate. + * + * Like + * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), + * it only emits a value from the source if it passes a criterion function. + * + * + * + * Similar to the well-known `Array.prototype.filter` method, this operator + * takes values from the source Observable, passes them through a `predicate` + * function and only emits those values that yielded `true`. + * + * @example Emit only click events whose target was a DIV element + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV'); + * clicksOnDivs.subscribe(x => console.log(x)); + * + * @see {@link distinct} + * @see {@link distinctUntilChanged} + * @see {@link distinctUntilKeyChanged} + * @see {@link ignoreElements} + * @see {@link partition} + * @see {@link skip} + * + * @param {function(value: T, index: number): boolean} predicate A function that + * evaluates each value emitted by the source Observable. If it returns `true`, + * the value is emitted, if `false` the value is not passed to the output + * Observable. The `index` parameter is the number `i` for the i-th source + * emission that has happened since the subscription, starting from the number + * `0`. + * @param {any} [thisArg] An optional argument to determine the value of `this` + * in the `predicate` function. + * @return {Observable} An Observable of values from the source that were + * allowed by the `predicate` function. + * @method filter + * @owner Observable + */ +function filter(predicate, thisArg) { + return function filterOperatorFunction(source) { + return source.lift(new FilterOperator(predicate, thisArg)); + }; +} +exports.filter = filter; +var FilterOperator = (function () { + function FilterOperator(predicate, thisArg) { + this.predicate = predicate; + this.thisArg = thisArg; + } + FilterOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); + }; + return FilterOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var FilterSubscriber = (function (_super) { + __extends(FilterSubscriber, _super); + function FilterSubscriber(destination, predicate, thisArg) { + _super.call(this, destination); + this.predicate = predicate; + this.thisArg = thisArg; + this.count = 0; + } + // the try catch block below is left specifically for + // optimization and perf reasons. a tryCatcher is not necessary here. + FilterSubscriber.prototype._next = function (value) { + var result; + try { + result = this.predicate.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + this.destination.next(value); + } + }; + return FilterSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],175:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var Subscription_1 = require('../Subscription'); +/** + * Returns an Observable that mirrors the source Observable, but will call a specified function when + * the source terminates on complete or error. + * @param {function} callback Function to be called when source terminates. + * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination. + * @method finally + * @owner Observable + */ +function finalize(callback) { + return function (source) { return source.lift(new FinallyOperator(callback)); }; +} +exports.finalize = finalize; +var FinallyOperator = (function () { + function FinallyOperator(callback) { + this.callback = callback; + } + FinallyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new FinallySubscriber(subscriber, this.callback)); + }; + return FinallyOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var FinallySubscriber = (function (_super) { + __extends(FinallySubscriber, _super); + function FinallySubscriber(destination, callback) { + _super.call(this, destination); + this.add(new Subscription_1.Subscription(callback)); + } + return FinallySubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36,"../Subscription":37}],176:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var EmptyError_1 = require('../util/EmptyError'); +/** + * Emits only the first value (or the first value that meets some condition) + * emitted by the source Observable. + * + * Emits only the first value. Or emits only the first + * value that passes some test. + * + * + * + * If called with no arguments, `first` emits the first value of the source + * Observable, then completes. If called with a `predicate` function, `first` + * emits the first value of the source that matches the specified condition. It + * may also take a `resultSelector` function to produce the output value from + * the input value, and a `defaultValue` to emit in case the source completes + * before it is able to emit a valid value. Throws an error if `defaultValue` + * was not provided and a matching element is not found. + * + * @example Emit only the first click that happens on the DOM + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.first(); + * result.subscribe(x => console.log(x)); + * + * @example Emits the first click that happens on a DIV + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.first(ev => ev.target.tagName === 'DIV'); + * result.subscribe(x => console.log(x)); + * + * @see {@link filter} + * @see {@link find} + * @see {@link take} + * + * @throws {EmptyError} Delivers an EmptyError to the Observer's `error` + * callback if the Observable completes before any `next` notification was sent. + * + * @param {function(value: T, index: number, source: Observable): boolean} [predicate] + * An optional function called with each item to test for condition matching. + * @param {function(value: T, index: number): R} [resultSelector] A function to + * produce the value on the output Observable based on the values + * and the indices of the source Observable. The arguments passed to this + * function are: + * - `value`: the value that was emitted on the source. + * - `index`: the "index" of the value from the source. + * @param {R} [defaultValue] The default value emitted in case no valid value + * was found on the source. + * @return {Observable} An Observable of the first item that matches the + * condition. + * @method first + * @owner Observable + */ +function first(predicate, resultSelector, defaultValue) { + return function (source) { return source.lift(new FirstOperator(predicate, resultSelector, defaultValue, source)); }; +} +exports.first = first; +var FirstOperator = (function () { + function FirstOperator(predicate, resultSelector, defaultValue, source) { + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + } + FirstOperator.prototype.call = function (observer, source) { + return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source)); + }; + return FirstOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var FirstSubscriber = (function (_super) { + __extends(FirstSubscriber, _super); + function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) { + _super.call(this, destination); + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + this.index = 0; + this.hasCompleted = false; + this._emitted = false; + } + FirstSubscriber.prototype._next = function (value) { + var index = this.index++; + if (this.predicate) { + this._tryPredicate(value, index); + } + else { + this._emit(value, index); + } + }; + FirstSubscriber.prototype._tryPredicate = function (value, index) { + var result; + try { + result = this.predicate(value, index, this.source); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + this._emit(value, index); + } + }; + FirstSubscriber.prototype._emit = function (value, index) { + if (this.resultSelector) { + this._tryResultSelector(value, index); + return; + } + this._emitFinal(value); + }; + FirstSubscriber.prototype._tryResultSelector = function (value, index) { + var result; + try { + result = this.resultSelector(value, index); + } + catch (err) { + this.destination.error(err); + return; + } + this._emitFinal(result); + }; + FirstSubscriber.prototype._emitFinal = function (value) { + var destination = this.destination; + if (!this._emitted) { + this._emitted = true; + destination.next(value); + destination.complete(); + this.hasCompleted = true; + } + }; + FirstSubscriber.prototype._complete = function () { + var destination = this.destination; + if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') { + destination.next(this.defaultValue); + destination.complete(); + } + else if (!this.hasCompleted) { + destination.error(new EmptyError_1.EmptyError); + } + }; + return FirstSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36,"../util/EmptyError":219}],177:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var EmptyError_1 = require('../util/EmptyError'); +/* tslint:enable:max-line-length */ +/** + * Returns an Observable that emits only the last item emitted by the source Observable. + * It optionally takes a predicate function as a parameter, in which case, rather than emitting + * the last item from the source Observable, the resulting Observable will emit the last item + * from the source Observable that satisfies the predicate. + * + * + * + * @throws {EmptyError} Delivers an EmptyError to the Observer's `error` + * callback if the Observable completes before any `next` notification was sent. + * @param {function} predicate - The condition any source emitted item has to satisfy. + * @return {Observable} An Observable that emits only the last item satisfying the given condition + * from the source, or an NoSuchElementException if no such items are emitted. + * @throws - Throws if no items that match the predicate are emitted by the source Observable. + * @method last + * @owner Observable + */ +function last(predicate, resultSelector, defaultValue) { + return function (source) { return source.lift(new LastOperator(predicate, resultSelector, defaultValue, source)); }; +} +exports.last = last; +var LastOperator = (function () { + function LastOperator(predicate, resultSelector, defaultValue, source) { + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + } + LastOperator.prototype.call = function (observer, source) { + return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source)); + }; + return LastOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var LastSubscriber = (function (_super) { + __extends(LastSubscriber, _super); + function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) { + _super.call(this, destination); + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + this.hasValue = false; + this.index = 0; + if (typeof defaultValue !== 'undefined') { + this.lastValue = defaultValue; + this.hasValue = true; + } + } + LastSubscriber.prototype._next = function (value) { + var index = this.index++; + if (this.predicate) { + this._tryPredicate(value, index); + } + else { + if (this.resultSelector) { + this._tryResultSelector(value, index); + return; + } + this.lastValue = value; + this.hasValue = true; + } + }; + LastSubscriber.prototype._tryPredicate = function (value, index) { + var result; + try { + result = this.predicate(value, index, this.source); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + if (this.resultSelector) { + this._tryResultSelector(value, index); + return; + } + this.lastValue = value; + this.hasValue = true; + } + }; + LastSubscriber.prototype._tryResultSelector = function (value, index) { + var result; + try { + result = this.resultSelector(value, index); + } + catch (err) { + this.destination.error(err); + return; + } + this.lastValue = result; + this.hasValue = true; + }; + LastSubscriber.prototype._complete = function () { + var destination = this.destination; + if (this.hasValue) { + destination.next(this.lastValue); + destination.complete(); + } + else { + destination.error(new EmptyError_1.EmptyError); + } + }; + return LastSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36,"../util/EmptyError":219}],178:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/** + * Applies a given `project` function to each value emitted by the source + * Observable, and emits the resulting values as an Observable. + * + * Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), + * it passes each source value through a transformation function to get + * corresponding output values. + * + * + * + * Similar to the well known `Array.prototype.map` function, this operator + * applies a projection to each value and emits that projection in the output + * Observable. + * + * @example Map every click to the clientX position of that click + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var positions = clicks.map(ev => ev.clientX); + * positions.subscribe(x => console.log(x)); + * + * @see {@link mapTo} + * @see {@link pluck} + * + * @param {function(value: T, index: number): R} project The function to apply + * to each `value` emitted by the source Observable. The `index` parameter is + * the number `i` for the i-th emission that has happened since the + * subscription, starting from the number `0`. + * @param {any} [thisArg] An optional argument to define what `this` is in the + * `project` function. + * @return {Observable} An Observable that emits the values from the source + * Observable transformed by the given `project` function. + * @method map + * @owner Observable + */ +function map(project, thisArg) { + return function mapOperation(source) { + if (typeof project !== 'function') { + throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); + } + return source.lift(new MapOperator(project, thisArg)); + }; +} +exports.map = map; +var MapOperator = (function () { + function MapOperator(project, thisArg) { + this.project = project; + this.thisArg = thisArg; + } + MapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); + }; + return MapOperator; +}()); +exports.MapOperator = MapOperator; +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var MapSubscriber = (function (_super) { + __extends(MapSubscriber, _super); + function MapSubscriber(destination, project, thisArg) { + _super.call(this, destination); + this.project = project; + this.count = 0; + this.thisArg = thisArg || this; + } + // NOTE: This looks unoptimized, but it's actually purposefully NOT + // using try/catch optimizations. + MapSubscriber.prototype._next = function (value) { + var result; + try { + result = this.project.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return MapSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],179:[function(require,module,exports){ +"use strict"; +var Observable_1 = require('../Observable'); +var ArrayObservable_1 = require('../observable/ArrayObservable'); +var mergeAll_1 = require('./mergeAll'); +var isScheduler_1 = require('../util/isScheduler'); +/* tslint:enable:max-line-length */ +function merge() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + return function (source) { return source.lift.call(mergeStatic.apply(void 0, [source].concat(observables))); }; +} +exports.merge = merge; +/* tslint:enable:max-line-length */ +/** + * Creates an output Observable which concurrently emits all values from every + * given input Observable. + * + * Flattens multiple Observables together by blending + * their values into one Observable. + * + * + * + * `merge` subscribes to each given input Observable (as arguments), and simply + * forwards (without doing any transformation) all the values from all the input + * Observables to the output Observable. The output Observable only completes + * once all input Observables have completed. Any error delivered by an input + * Observable will be immediately emitted on the output Observable. + * + * @example Merge together two Observables: 1s interval and clicks + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var timer = Rx.Observable.interval(1000); + * var clicksOrTimer = Rx.Observable.merge(clicks, timer); + * clicksOrTimer.subscribe(x => console.log(x)); + * + * // Results in the following: + * // timer will emit ascending values, one every second(1000ms) to console + * // clicks logs MouseEvents to console everytime the "document" is clicked + * // Since the two streams are merged you see these happening + * // as they occur. + * + * @example Merge together 3 Observables, but only 2 run concurrently + * var timer1 = Rx.Observable.interval(1000).take(10); + * var timer2 = Rx.Observable.interval(2000).take(6); + * var timer3 = Rx.Observable.interval(500).take(10); + * var concurrent = 2; // the argument + * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent); + * merged.subscribe(x => console.log(x)); + * + * // Results in the following: + * // - First timer1 and timer2 will run concurrently + * // - timer1 will emit a value every 1000ms for 10 iterations + * // - timer2 will emit a value every 2000ms for 6 iterations + * // - after timer1 hits it's max iteration, timer2 will + * // continue, and timer3 will start to run concurrently with timer2 + * // - when timer2 hits it's max iteration it terminates, and + * // timer3 will continue to emit a value every 500ms until it is complete + * + * @see {@link mergeAll} + * @see {@link mergeMap} + * @see {@link mergeMapTo} + * @see {@link mergeScan} + * + * @param {...ObservableInput} observables Input Observables to merge together. + * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input + * Observables being subscribed to concurrently. + * @param {Scheduler} [scheduler=null] The IScheduler to use for managing + * concurrency of input Observables. + * @return {Observable} an Observable that emits items that are the result of + * every input Observable. + * @static true + * @name merge + * @owner Observable + */ +function mergeStatic() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var concurrent = Number.POSITIVE_INFINITY; + var scheduler = null; + var last = observables[observables.length - 1]; + if (isScheduler_1.isScheduler(last)) { + scheduler = observables.pop(); + if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') { + concurrent = observables.pop(); + } + } + else if (typeof last === 'number') { + concurrent = observables.pop(); + } + if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) { + return observables[0]; + } + return mergeAll_1.mergeAll(concurrent)(new ArrayObservable_1.ArrayObservable(observables, scheduler)); +} +exports.mergeStatic = mergeStatic; + +},{"../Observable":29,"../observable/ArrayObservable":93,"../util/isScheduler":233,"./mergeAll":180}],180:[function(require,module,exports){ +"use strict"; +var mergeMap_1 = require('./mergeMap'); +var identity_1 = require('../util/identity'); +/** + * Converts a higher-order Observable into a first-order Observable which + * concurrently delivers all values that are emitted on the inner Observables. + * + * Flattens an Observable-of-Observables. + * + * + * + * `mergeAll` subscribes to an Observable that emits Observables, also known as + * a higher-order Observable. Each time it observes one of these emitted inner + * Observables, it subscribes to that and delivers all the values from the + * inner Observable on the output Observable. The output Observable only + * completes once all inner Observables have completed. Any error delivered by + * a inner Observable will be immediately emitted on the output Observable. + * + * @example Spawn a new interval Observable for each click event, and blend their outputs as one Observable + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000)); + * var firstOrder = higherOrder.mergeAll(); + * firstOrder.subscribe(x => console.log(x)); + * + * @example Count from 0 to 9 every second for each click, but only allow 2 concurrent timers + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10)); + * var firstOrder = higherOrder.mergeAll(2); + * firstOrder.subscribe(x => console.log(x)); + * + * @see {@link combineAll} + * @see {@link concatAll} + * @see {@link exhaust} + * @see {@link merge} + * @see {@link mergeMap} + * @see {@link mergeMapTo} + * @see {@link mergeScan} + * @see {@link switch} + * @see {@link zipAll} + * + * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner + * Observables being subscribed to concurrently. + * @return {Observable} An Observable that emits values coming from all the + * inner Observables emitted by the source Observable. + * @method mergeAll + * @owner Observable + */ +function mergeAll(concurrent) { + if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } + return mergeMap_1.mergeMap(identity_1.identity, null, concurrent); +} +exports.mergeAll = mergeAll; + +},{"../util/identity":225,"./mergeMap":181}],181:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var subscribeToResult_1 = require('../util/subscribeToResult'); +var OuterSubscriber_1 = require('../OuterSubscriber'); +/* tslint:enable:max-line-length */ +/** + * Projects each source value to an Observable which is merged in the output + * Observable. + * + * Maps each value to an Observable, then flattens all of + * these inner Observables using {@link mergeAll}. + * + * + * + * Returns an Observable that emits items based on applying a function that you + * supply to each item emitted by the source Observable, where that function + * returns an Observable, and then merging those resulting Observables and + * emitting the results of this merger. + * + * @example Map and flatten each letter to an Observable ticking every 1 second + * var letters = Rx.Observable.of('a', 'b', 'c'); + * var result = letters.mergeMap(x => + * Rx.Observable.interval(1000).map(i => x+i) + * ); + * result.subscribe(x => console.log(x)); + * + * // Results in the following: + * // a0 + * // b0 + * // c0 + * // a1 + * // b1 + * // c1 + * // continues to list a,b,c with respective ascending integers + * + * @see {@link concatMap} + * @see {@link exhaustMap} + * @see {@link merge} + * @see {@link mergeAll} + * @see {@link mergeMapTo} + * @see {@link mergeScan} + * @see {@link switchMap} + * + * @param {function(value: T, ?index: number): ObservableInput} project A function + * that, when applied to an item emitted by the source Observable, returns an + * Observable. + * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector] + * A function to produce the value on the output Observable based on the values + * and the indices of the source (outer) emission and the inner Observable + * emission. The arguments passed to this function are: + * - `outerValue`: the value that came from the source + * - `innerValue`: the value that came from the projected Observable + * - `outerIndex`: the "index" of the value that came from the source + * - `innerIndex`: the "index" of the value from the projected Observable + * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input + * Observables being subscribed to concurrently. + * @return {Observable} An Observable that emits the result of applying the + * projection function (and the optional `resultSelector`) to each item emitted + * by the source Observable and merging the results of the Observables obtained + * from this transformation. + * @method mergeMap + * @owner Observable + */ +function mergeMap(project, resultSelector, concurrent) { + if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } + return function mergeMapOperatorFunction(source) { + if (typeof resultSelector === 'number') { + concurrent = resultSelector; + resultSelector = null; + } + return source.lift(new MergeMapOperator(project, resultSelector, concurrent)); + }; +} +exports.mergeMap = mergeMap; +var MergeMapOperator = (function () { + function MergeMapOperator(project, resultSelector, concurrent) { + if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } + this.project = project; + this.resultSelector = resultSelector; + this.concurrent = concurrent; + } + MergeMapOperator.prototype.call = function (observer, source) { + return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent)); + }; + return MergeMapOperator; +}()); +exports.MergeMapOperator = MergeMapOperator; +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var MergeMapSubscriber = (function (_super) { + __extends(MergeMapSubscriber, _super); + function MergeMapSubscriber(destination, project, resultSelector, concurrent) { + if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } + _super.call(this, destination); + this.project = project; + this.resultSelector = resultSelector; + this.concurrent = concurrent; + this.hasCompleted = false; + this.buffer = []; + this.active = 0; + this.index = 0; + } + MergeMapSubscriber.prototype._next = function (value) { + if (this.active < this.concurrent) { + this._tryNext(value); + } + else { + this.buffer.push(value); + } + }; + MergeMapSubscriber.prototype._tryNext = function (value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } + catch (err) { + this.destination.error(err); + return; + } + this.active++; + this._innerSub(result, value, index); + }; + MergeMapSubscriber.prototype._innerSub = function (ish, value, index) { + this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index)); + }; + MergeMapSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + this.destination.complete(); + } + }; + MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (this.resultSelector) { + this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex); + } + else { + this.destination.next(innerValue); + } + }; + MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) { + var result; + try { + result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + MergeMapSubscriber.prototype.notifyComplete = function (innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); + } + else if (this.active === 0 && this.hasCompleted) { + this.destination.complete(); + } + }; + return MergeMapSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); +exports.MergeMapSubscriber = MergeMapSubscriber; + +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],182:[function(require,module,exports){ +"use strict"; +var ConnectableObservable_1 = require('../observable/ConnectableObservable'); +/* tslint:enable:max-line-length */ +/** + * Returns an Observable that emits the results of invoking a specified selector on items + * emitted by a ConnectableObservable that shares a single subscription to the underlying stream. + * + * + * + * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through + * which the source sequence's elements will be multicast to the selector function + * or Subject to push source elements into. + * @param {Function} [selector] - Optional selector function that can use the multicasted source stream + * as many times as needed, without causing multiple subscriptions to the source stream. + * Subscribers to the given source will receive all notifications of the source from the + * time of the subscription forward. + * @return {Observable} An Observable that emits the results of invoking the selector + * on the items emitted by a `ConnectableObservable` that shares a single subscription to + * the underlying stream. + * @method multicast + * @owner Observable + */ +function multicast(subjectOrSubjectFactory, selector) { + return function multicastOperatorFunction(source) { + var subjectFactory; + if (typeof subjectOrSubjectFactory === 'function') { + subjectFactory = subjectOrSubjectFactory; + } + else { + subjectFactory = function subjectFactory() { + return subjectOrSubjectFactory; + }; + } + if (typeof selector === 'function') { + return source.lift(new MulticastOperator(subjectFactory, selector)); + } + var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor); + connectable.source = source; + connectable.subjectFactory = subjectFactory; + return connectable; + }; +} +exports.multicast = multicast; +var MulticastOperator = (function () { + function MulticastOperator(subjectFactory, selector) { + this.subjectFactory = subjectFactory; + this.selector = selector; + } + MulticastOperator.prototype.call = function (subscriber, source) { + var selector = this.selector; + var subject = this.subjectFactory(); + var subscription = selector(subject).subscribe(subscriber); + subscription.add(source.subscribe(subject)); + return subscription; + }; + return MulticastOperator; +}()); +exports.MulticastOperator = MulticastOperator; + +},{"../observable/ConnectableObservable":94}],183:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var Notification_1 = require('../Notification'); +/** + * + * Re-emits all notifications from source Observable with specified scheduler. + * + * Ensure a specific scheduler is used, from outside of an Observable. + * + * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule + * notifications emitted by the source Observable. It might be useful, if you do not have control over + * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless. + * + * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable, + * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal + * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits + * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`. + * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split + * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source + * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a + * little bit more, to ensure that they are emitted at expected moments. + * + * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications + * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn` + * will delay all notifications - including error notifications - while `delay` will pass through error + * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator + * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used + * for notification emissions in general. + * + * @example Ensure values in subscribe are called just before browser repaint. + * const intervals = Rx.Observable.interval(10); // Intervals are scheduled + * // with async scheduler by default... + * + * intervals + * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame + * .subscribe(val => { // scheduler to ensure smooth animation. + * someDiv.style.height = val + 'px'; + * }); + * + * @see {@link delay} + * + * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable. + * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled. + * @return {Observable} Observable that emits the same notifications as the source Observable, + * but with provided scheduler. + * + * @method observeOn + * @owner Observable + */ +function observeOn(scheduler, delay) { + if (delay === void 0) { delay = 0; } + return function observeOnOperatorFunction(source) { + return source.lift(new ObserveOnOperator(scheduler, delay)); + }; +} +exports.observeOn = observeOn; +var ObserveOnOperator = (function () { + function ObserveOnOperator(scheduler, delay) { + if (delay === void 0) { delay = 0; } + this.scheduler = scheduler; + this.delay = delay; + } + ObserveOnOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay)); + }; + return ObserveOnOperator; +}()); +exports.ObserveOnOperator = ObserveOnOperator; +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var ObserveOnSubscriber = (function (_super) { + __extends(ObserveOnSubscriber, _super); + function ObserveOnSubscriber(destination, scheduler, delay) { + if (delay === void 0) { delay = 0; } + _super.call(this, destination); + this.scheduler = scheduler; + this.delay = delay; + } + ObserveOnSubscriber.dispatch = function (arg) { + var notification = arg.notification, destination = arg.destination; + notification.observe(destination); + this.unsubscribe(); + }; + ObserveOnSubscriber.prototype.scheduleMessage = function (notification) { + this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination))); + }; + ObserveOnSubscriber.prototype._next = function (value) { + this.scheduleMessage(Notification_1.Notification.createNext(value)); + }; + ObserveOnSubscriber.prototype._error = function (err) { + this.scheduleMessage(Notification_1.Notification.createError(err)); + }; + ObserveOnSubscriber.prototype._complete = function () { + this.scheduleMessage(Notification_1.Notification.createComplete()); + }; + return ObserveOnSubscriber; +}(Subscriber_1.Subscriber)); +exports.ObserveOnSubscriber = ObserveOnSubscriber; +var ObserveOnMessage = (function () { + function ObserveOnMessage(notification, destination) { + this.notification = notification; + this.destination = destination; + } + return ObserveOnMessage; +}()); +exports.ObserveOnMessage = ObserveOnMessage; + +},{"../Notification":28,"../Subscriber":36}],184:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/** + * Groups pairs of consecutive emissions together and emits them as an array of + * two values. + * + * Puts the current value and previous value together as + * an array, and emits that. + * + * + * + * The Nth emission from the source Observable will cause the output Observable + * to emit an array [(N-1)th, Nth] of the previous and the current value, as a + * pair. For this reason, `pairwise` emits on the second and subsequent + * emissions from the source Observable, but not on the first emission, because + * there is no previous value in that case. + * + * @example On every click (starting from the second), emit the relative distance to the previous click + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var pairs = clicks.pairwise(); + * var distance = pairs.map(pair => { + * var x0 = pair[0].clientX; + * var y0 = pair[0].clientY; + * var x1 = pair[1].clientX; + * var y1 = pair[1].clientY; + * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2)); + * }); + * distance.subscribe(x => console.log(x)); + * + * @see {@link buffer} + * @see {@link bufferCount} + * + * @return {Observable>} An Observable of pairs (as arrays) of + * consecutive values from the source Observable. + * @method pairwise + * @owner Observable + */ +function pairwise() { + return function (source) { return source.lift(new PairwiseOperator()); }; +} +exports.pairwise = pairwise; +var PairwiseOperator = (function () { + function PairwiseOperator() { + } + PairwiseOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new PairwiseSubscriber(subscriber)); + }; + return PairwiseOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var PairwiseSubscriber = (function (_super) { + __extends(PairwiseSubscriber, _super); + function PairwiseSubscriber(destination) { + _super.call(this, destination); + this.hasPrev = false; + } + PairwiseSubscriber.prototype._next = function (value) { + if (this.hasPrev) { + this.destination.next([this.prev, value]); + } + else { + this.hasPrev = true; + } + this.prev = value; + }; + return PairwiseSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],185:[function(require,module,exports){ +"use strict"; +var map_1 = require('./map'); +/** + * Maps each source value (an object) to its specified nested property. + * + * Like {@link map}, but meant only for picking one of + * the nested properties of every emitted object. + * + * + * + * Given a list of strings describing a path to an object property, retrieves + * the value of a specified nested property from all values in the source + * Observable. If a property can't be resolved, it will return `undefined` for + * that value. + * + * @example Map every click to the tagName of the clicked target element + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var tagNames = clicks.pluck('target', 'tagName'); + * tagNames.subscribe(x => console.log(x)); + * + * @see {@link map} + * + * @param {...string} properties The nested properties to pluck from each source + * value (an object). + * @return {Observable} A new Observable of property values from the source values. + * @method pluck + * @owner Observable + */ +function pluck() { + var properties = []; + for (var _i = 0; _i < arguments.length; _i++) { + properties[_i - 0] = arguments[_i]; + } + var length = properties.length; + if (length === 0) { + throw new Error('list of properties cannot be empty.'); + } + return function (source) { return map_1.map(plucker(properties, length))(source); }; +} +exports.pluck = pluck; +function plucker(props, length) { + var mapper = function (x) { + var currentProp = x; + for (var i = 0; i < length; i++) { + var p = currentProp[props[i]]; + if (typeof p !== 'undefined') { + currentProp = p; + } + else { + return undefined; + } + } + return currentProp; + }; + return mapper; +} + +},{"./map":178}],186:[function(require,module,exports){ +"use strict"; +var Subject_1 = require('../Subject'); +var multicast_1 = require('./multicast'); +/* tslint:enable:max-line-length */ +/** + * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called + * before it begins emitting items to those Observers that have subscribed to it. + * + * + * + * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times + * as needed, without causing multiple subscriptions to the source sequence. + * Subscribers to the given source will receive all notifications of the source from the time of the subscription on. + * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers. + * @method publish + * @owner Observable + */ +function publish(selector) { + return selector ? + multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) : + multicast_1.multicast(new Subject_1.Subject()); +} +exports.publish = publish; + +},{"../Subject":34,"./multicast":182}],187:[function(require,module,exports){ +"use strict"; +var ReplaySubject_1 = require('../ReplaySubject'); +var multicast_1 = require('./multicast'); +/* tslint:enable:max-line-length */ +function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) { + if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') { + scheduler = selectorOrScheduler; + } + var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined; + var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler); + return function (source) { return multicast_1.multicast(function () { return subject; }, selector)(source); }; +} +exports.publishReplay = publishReplay; + +},{"../ReplaySubject":32,"./multicast":182}],188:[function(require,module,exports){ +"use strict"; +var scan_1 = require('./scan'); +var takeLast_1 = require('./takeLast'); +var defaultIfEmpty_1 = require('./defaultIfEmpty'); +var pipe_1 = require('../util/pipe'); +/* tslint:enable:max-line-length */ +/** + * Applies an accumulator function over the source Observable, and returns the + * accumulated result when the source completes, given an optional seed value. + * + * Combines together all values emitted on the source, + * using an accumulator function that knows how to join a new source value into + * the accumulation from the past. + * + * + * + * Like + * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce), + * `reduce` applies an `accumulator` function against an accumulation and each + * value of the source Observable (from the past) to reduce it to a single + * value, emitted on the output Observable. Note that `reduce` will only emit + * one value, only when the source Observable completes. It is equivalent to + * applying operator {@link scan} followed by operator {@link last}. + * + * Returns an Observable that applies a specified `accumulator` function to each + * item emitted by the source Observable. If a `seed` value is specified, then + * that value will be used as the initial value for the accumulator. If no seed + * value is specified, the first item of the source is used as the seed. + * + * @example Count the number of click events that happened in 5 seconds + * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click') + * .takeUntil(Rx.Observable.interval(5000)); + * var ones = clicksInFiveSeconds.mapTo(1); + * var seed = 0; + * var count = ones.reduce((acc, one) => acc + one, seed); + * count.subscribe(x => console.log(x)); + * + * @see {@link count} + * @see {@link expand} + * @see {@link mergeScan} + * @see {@link scan} + * + * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function + * called on each source value. + * @param {R} [seed] The initial accumulation value. + * @return {Observable} An Observable that emits a single value that is the + * result of accumulating the values emitted by the source Observable. + * @method reduce + * @owner Observable + */ +function reduce(accumulator, seed) { + // providing a seed of `undefined` *should* be valid and trigger + // hasSeed! so don't use `seed !== undefined` checks! + // For this reason, we have to check it here at the original call site + // otherwise inside Operator/Subscriber we won't know if `undefined` + // means they didn't provide anything or if they literally provided `undefined` + if (arguments.length >= 2) { + return function reduceOperatorFunctionWithSeed(source) { + return pipe_1.pipe(scan_1.scan(accumulator, seed), takeLast_1.takeLast(1), defaultIfEmpty_1.defaultIfEmpty(seed))(source); + }; + } + return function reduceOperatorFunction(source) { + return pipe_1.pipe(scan_1.scan(function (acc, value, index) { + return accumulator(acc, value, index + 1); + }), takeLast_1.takeLast(1))(source); + }; +} +exports.reduce = reduce; + +},{"../util/pipe":235,"./defaultIfEmpty":169,"./scan":192,"./takeLast":200}],189:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +function refCount() { + return function refCountOperatorFunction(source) { + return source.lift(new RefCountOperator(source)); + }; +} +exports.refCount = refCount; +var RefCountOperator = (function () { + function RefCountOperator(connectable) { + this.connectable = connectable; + } + RefCountOperator.prototype.call = function (subscriber, source) { + var connectable = this.connectable; + connectable._refCount++; + var refCounter = new RefCountSubscriber(subscriber, connectable); + var subscription = source.subscribe(refCounter); + if (!refCounter.closed) { + refCounter.connection = connectable.connect(); + } + return subscription; + }; + return RefCountOperator; +}()); +var RefCountSubscriber = (function (_super) { + __extends(RefCountSubscriber, _super); + function RefCountSubscriber(destination, connectable) { + _super.call(this, destination); + this.connectable = connectable; + } + RefCountSubscriber.prototype._unsubscribe = function () { + var connectable = this.connectable; + if (!connectable) { + this.connection = null; + return; + } + this.connectable = null; + var refCount = connectable._refCount; + if (refCount <= 0) { + this.connection = null; + return; + } + connectable._refCount = refCount - 1; + if (refCount > 1) { + this.connection = null; + return; + } + /// + // Compare the local RefCountSubscriber's connection Subscription to the + // connection Subscription on the shared ConnectableObservable. In cases + // where the ConnectableObservable source synchronously emits values, and + // the RefCountSubscriber's downstream Observers synchronously unsubscribe, + // execution continues to here before the RefCountOperator has a chance to + // supply the RefCountSubscriber with the shared connection Subscription. + // For example: + // ``` + // Observable.range(0, 10) + // .publish() + // .refCount() + // .take(5) + // .subscribe(); + // ``` + // In order to account for this case, RefCountSubscriber should only dispose + // the ConnectableObservable's shared connection Subscription if the + // connection Subscription exists, *and* either: + // a. RefCountSubscriber doesn't have a reference to the shared connection + // Subscription yet, or, + // b. RefCountSubscriber's connection Subscription reference is identical + // to the shared connection Subscription + /// + var connection = this.connection; + var sharedConnection = connectable._connection; + this.connection = null; + if (sharedConnection && (!connection || sharedConnection === connection)) { + sharedConnection.unsubscribe(); + } + }; + return RefCountSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],190:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/** + * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable + * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given + * as a number parameter) rather than propagating the `error` call. + * + * + * + * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted + * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second + * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications + * would be: [1, 2, 1, 2, 3, 4, 5, `complete`]. + * @param {number} count - Number of retry attempts before failing. + * @return {Observable} The source Observable modified with the retry logic. + * @method retry + * @owner Observable + */ +function retry(count) { + if (count === void 0) { count = -1; } + return function (source) { return source.lift(new RetryOperator(count, source)); }; +} +exports.retry = retry; +var RetryOperator = (function () { + function RetryOperator(count, source) { + this.count = count; + this.source = source; + } + RetryOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source)); + }; + return RetryOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var RetrySubscriber = (function (_super) { + __extends(RetrySubscriber, _super); + function RetrySubscriber(destination, count, source) { + _super.call(this, destination); + this.count = count; + this.source = source; + } + RetrySubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _a = this, source = _a.source, count = _a.count; + if (count === 0) { + return _super.prototype.error.call(this, err); + } + else if (count > -1) { + this.count = count - 1; + } + source.subscribe(this._unsubscribeAndRecycle()); + } + }; + return RetrySubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],191:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/** + * Emits the most recently emitted value from the source Observable whenever + * another Observable, the `notifier`, emits. + * + * It's like {@link sampleTime}, but samples whenever + * the `notifier` Observable emits something. + * + * + * + * Whenever the `notifier` Observable emits a value or completes, `sample` + * looks at the source Observable and emits whichever value it has most recently + * emitted since the previous sampling, unless the source has not emitted + * anything since the previous sampling. The `notifier` is subscribed to as soon + * as the output Observable is subscribed. + * + * @example On every click, sample the most recent "seconds" timer + * var seconds = Rx.Observable.interval(1000); + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = seconds.sample(clicks); + * result.subscribe(x => console.log(x)); + * + * @see {@link audit} + * @see {@link debounce} + * @see {@link sampleTime} + * @see {@link throttle} + * + * @param {Observable} notifier The Observable to use for sampling the + * source Observable. + * @return {Observable} An Observable that emits the results of sampling the + * values emitted by the source Observable whenever the notifier Observable + * emits value or completes. + * @method sample + * @owner Observable + */ +function sample(notifier) { + return function (source) { return source.lift(new SampleOperator(notifier)); }; +} +exports.sample = sample; +var SampleOperator = (function () { + function SampleOperator(notifier) { + this.notifier = notifier; + } + SampleOperator.prototype.call = function (subscriber, source) { + var sampleSubscriber = new SampleSubscriber(subscriber); + var subscription = source.subscribe(sampleSubscriber); + subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier)); + return subscription; + }; + return SampleOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var SampleSubscriber = (function (_super) { + __extends(SampleSubscriber, _super); + function SampleSubscriber() { + _super.apply(this, arguments); + this.hasValue = false; + } + SampleSubscriber.prototype._next = function (value) { + this.value = value; + this.hasValue = true; + }; + SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.emitValue(); + }; + SampleSubscriber.prototype.notifyComplete = function () { + this.emitValue(); + }; + SampleSubscriber.prototype.emitValue = function () { + if (this.hasValue) { + this.hasValue = false; + this.destination.next(this.value); + } + }; + return SampleSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); + +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],192:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/* tslint:enable:max-line-length */ +/** + * Applies an accumulator function over the source Observable, and returns each + * intermediate result, with an optional seed value. + * + * It's like {@link reduce}, but emits the current + * accumulation whenever the source emits a value. + * + * + * + * Combines together all values emitted on the source, using an accumulator + * function that knows how to join a new source value into the accumulation from + * the past. Is similar to {@link reduce}, but emits the intermediate + * accumulations. + * + * Returns an Observable that applies a specified `accumulator` function to each + * item emitted by the source Observable. If a `seed` value is specified, then + * that value will be used as the initial value for the accumulator. If no seed + * value is specified, the first item of the source is used as the seed. + * + * @example Count the number of click events + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var ones = clicks.mapTo(1); + * var seed = 0; + * var count = ones.scan((acc, one) => acc + one, seed); + * count.subscribe(x => console.log(x)); + * + * @see {@link expand} + * @see {@link mergeScan} + * @see {@link reduce} + * + * @param {function(acc: R, value: T, index: number): R} accumulator + * The accumulator function called on each source value. + * @param {T|R} [seed] The initial accumulation value. + * @return {Observable} An observable of the accumulated values. + * @method scan + * @owner Observable + */ +function scan(accumulator, seed) { + var hasSeed = false; + // providing a seed of `undefined` *should* be valid and trigger + // hasSeed! so don't use `seed !== undefined` checks! + // For this reason, we have to check it here at the original call site + // otherwise inside Operator/Subscriber we won't know if `undefined` + // means they didn't provide anything or if they literally provided `undefined` + if (arguments.length >= 2) { + hasSeed = true; + } + return function scanOperatorFunction(source) { + return source.lift(new ScanOperator(accumulator, seed, hasSeed)); + }; +} +exports.scan = scan; +var ScanOperator = (function () { + function ScanOperator(accumulator, seed, hasSeed) { + if (hasSeed === void 0) { hasSeed = false; } + this.accumulator = accumulator; + this.seed = seed; + this.hasSeed = hasSeed; + } + ScanOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); + }; + return ScanOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var ScanSubscriber = (function (_super) { + __extends(ScanSubscriber, _super); + function ScanSubscriber(destination, accumulator, _seed, hasSeed) { + _super.call(this, destination); + this.accumulator = accumulator; + this._seed = _seed; + this.hasSeed = hasSeed; + this.index = 0; + } + Object.defineProperty(ScanSubscriber.prototype, "seed", { + get: function () { + return this._seed; + }, + set: function (value) { + this.hasSeed = true; + this._seed = value; + }, + enumerable: true, + configurable: true + }); + ScanSubscriber.prototype._next = function (value) { + if (!this.hasSeed) { + this.seed = value; + this.destination.next(value); + } + else { + return this._tryNext(value); + } + }; + ScanSubscriber.prototype._tryNext = function (value) { + var index = this.index++; + var result; + try { + result = this.accumulator(this.seed, value, index); + } + catch (err) { + this.destination.error(err); + } + this.seed = result; + this.destination.next(result); + }; + return ScanSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],193:[function(require,module,exports){ +"use strict"; +var multicast_1 = require('./multicast'); +var refCount_1 = require('./refCount'); +var Subject_1 = require('../Subject'); +function shareSubjectFactory() { + return new Subject_1.Subject(); +} +/** + * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one + * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will + * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`. + * This is an alias for .multicast(() => new Subject()).refCount(). + * + * + * + * @return {Observable} An Observable that upon connection causes the source Observable to emit items to its Observers. + * @method share + * @owner Observable + */ +function share() { + return function (source) { return refCount_1.refCount()(multicast_1.multicast(shareSubjectFactory)(source)); }; +} +exports.share = share; +; + +},{"../Subject":34,"./multicast":182,"./refCount":189}],194:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/** + * Returns an Observable that skips the first `count` items emitted by the source Observable. + * + * + * + * @param {Number} count - The number of times, items emitted by source Observable should be skipped. + * @return {Observable} An Observable that skips values emitted by the source Observable. + * + * @method skip + * @owner Observable + */ +function skip(count) { + return function (source) { return source.lift(new SkipOperator(count)); }; +} +exports.skip = skip; +var SkipOperator = (function () { + function SkipOperator(total) { + this.total = total; + } + SkipOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SkipSubscriber(subscriber, this.total)); + }; + return SkipOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var SkipSubscriber = (function (_super) { + __extends(SkipSubscriber, _super); + function SkipSubscriber(destination, total) { + _super.call(this, destination); + this.total = total; + this.count = 0; + } + SkipSubscriber.prototype._next = function (x) { + if (++this.count > this.total) { + this.destination.next(x); + } + }; + return SkipSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],195:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/** + * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item. + * + * + * + * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to + * be mirrored by the resulting Observable. + * @return {Observable} An Observable that skips items from the source Observable until the second Observable emits + * an item, then emits the remaining items. + * @method skipUntil + * @owner Observable + */ +function skipUntil(notifier) { + return function (source) { return source.lift(new SkipUntilOperator(notifier)); }; +} +exports.skipUntil = skipUntil; +var SkipUntilOperator = (function () { + function SkipUntilOperator(notifier) { + this.notifier = notifier; + } + SkipUntilOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier)); + }; + return SkipUntilOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var SkipUntilSubscriber = (function (_super) { + __extends(SkipUntilSubscriber, _super); + function SkipUntilSubscriber(destination, notifier) { + _super.call(this, destination); + this.hasValue = false; + this.isInnerStopped = false; + this.add(subscribeToResult_1.subscribeToResult(this, notifier)); + } + SkipUntilSubscriber.prototype._next = function (value) { + if (this.hasValue) { + _super.prototype._next.call(this, value); + } + }; + SkipUntilSubscriber.prototype._complete = function () { + if (this.isInnerStopped) { + _super.prototype._complete.call(this); + } + else { + this.unsubscribe(); + } + }; + SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.hasValue = true; + }; + SkipUntilSubscriber.prototype.notifyComplete = function () { + this.isInnerStopped = true; + if (this.isStopped) { + _super.prototype._complete.call(this); + } + }; + return SkipUntilSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); + +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],196:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/** + * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds + * true, but emits all further source items as soon as the condition becomes false. + * + * + * + * @param {Function} predicate - A function to test each item emitted from the source Observable. + * @return {Observable} An Observable that begins emitting items emitted by the source Observable when the + * specified predicate becomes false. + * @method skipWhile + * @owner Observable + */ +function skipWhile(predicate) { + return function (source) { return source.lift(new SkipWhileOperator(predicate)); }; +} +exports.skipWhile = skipWhile; +var SkipWhileOperator = (function () { + function SkipWhileOperator(predicate) { + this.predicate = predicate; + } + SkipWhileOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate)); + }; + return SkipWhileOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var SkipWhileSubscriber = (function (_super) { + __extends(SkipWhileSubscriber, _super); + function SkipWhileSubscriber(destination, predicate) { + _super.call(this, destination); + this.predicate = predicate; + this.skipping = true; + this.index = 0; + } + SkipWhileSubscriber.prototype._next = function (value) { + var destination = this.destination; + if (this.skipping) { + this.tryCallPredicate(value); + } + if (!this.skipping) { + destination.next(value); + } + }; + SkipWhileSubscriber.prototype.tryCallPredicate = function (value) { + try { + var result = this.predicate(value, this.index++); + this.skipping = Boolean(result); + } + catch (err) { + this.destination.error(err); + } + }; + return SkipWhileSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],197:[function(require,module,exports){ +"use strict"; +var ArrayObservable_1 = require('../observable/ArrayObservable'); +var ScalarObservable_1 = require('../observable/ScalarObservable'); +var EmptyObservable_1 = require('../observable/EmptyObservable'); +var concat_1 = require('../observable/concat'); +var isScheduler_1 = require('../util/isScheduler'); +/* tslint:enable:max-line-length */ +/** + * Returns an Observable that emits the items you specify as arguments before it begins to emit + * items emitted by the source Observable. + * + * + * + * @param {...T} values - Items you want the modified Observable to emit first. + * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling + * the emissions of the `next` notifications. + * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items + * emitted by the source Observable. + * @method startWith + * @owner Observable + */ +function startWith() { + var array = []; + for (var _i = 0; _i < arguments.length; _i++) { + array[_i - 0] = arguments[_i]; + } + return function (source) { + var scheduler = array[array.length - 1]; + if (isScheduler_1.isScheduler(scheduler)) { + array.pop(); + } + else { + scheduler = null; + } + var len = array.length; + if (len === 1) { + return concat_1.concat(new ScalarObservable_1.ScalarObservable(array[0], scheduler), source); + } + else if (len > 1) { + return concat_1.concat(new ArrayObservable_1.ArrayObservable(array, scheduler), source); + } + else { + return concat_1.concat(new EmptyObservable_1.EmptyObservable(scheduler), source); + } + }; +} +exports.startWith = startWith; + +},{"../observable/ArrayObservable":93,"../observable/EmptyObservable":96,"../observable/ScalarObservable":102,"../observable/concat":105,"../util/isScheduler":233}],198:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/* tslint:enable:max-line-length */ +/** + * Projects each source value to an Observable which is merged in the output + * Observable, emitting values only from the most recently projected Observable. + * + * Maps each value to an Observable, then flattens all of + * these inner Observables using {@link switch}. + * + * + * + * Returns an Observable that emits items based on applying a function that you + * supply to each item emitted by the source Observable, where that function + * returns an (so-called "inner") Observable. Each time it observes one of these + * inner Observables, the output Observable begins emitting the items emitted by + * that inner Observable. When a new inner Observable is emitted, `switchMap` + * stops emitting items from the earlier-emitted inner Observable and begins + * emitting items from the new one. It continues to behave like this for + * subsequent inner Observables. + * + * @example Rerun an interval Observable on every click event + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000)); + * result.subscribe(x => console.log(x)); + * + * @see {@link concatMap} + * @see {@link exhaustMap} + * @see {@link mergeMap} + * @see {@link switch} + * @see {@link switchMapTo} + * + * @param {function(value: T, ?index: number): ObservableInput} project A function + * that, when applied to an item emitted by the source Observable, returns an + * Observable. + * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector] + * A function to produce the value on the output Observable based on the values + * and the indices of the source (outer) emission and the inner Observable + * emission. The arguments passed to this function are: + * - `outerValue`: the value that came from the source + * - `innerValue`: the value that came from the projected Observable + * - `outerIndex`: the "index" of the value that came from the source + * - `innerIndex`: the "index" of the value from the projected Observable + * @return {Observable} An Observable that emits the result of applying the + * projection function (and the optional `resultSelector`) to each item emitted + * by the source Observable and taking only the values from the most recently + * projected inner Observable. + * @method switchMap + * @owner Observable + */ +function switchMap(project, resultSelector) { + return function switchMapOperatorFunction(source) { + return source.lift(new SwitchMapOperator(project, resultSelector)); + }; +} +exports.switchMap = switchMap; +var SwitchMapOperator = (function () { + function SwitchMapOperator(project, resultSelector) { + this.project = project; + this.resultSelector = resultSelector; + } + SwitchMapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector)); + }; + return SwitchMapOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var SwitchMapSubscriber = (function (_super) { + __extends(SwitchMapSubscriber, _super); + function SwitchMapSubscriber(destination, project, resultSelector) { + _super.call(this, destination); + this.project = project; + this.resultSelector = resultSelector; + this.index = 0; + } + SwitchMapSubscriber.prototype._next = function (value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } + catch (error) { + this.destination.error(error); + return; + } + this._innerSub(result, value, index); + }; + SwitchMapSubscriber.prototype._innerSub = function (result, value, index) { + var innerSubscription = this.innerSubscription; + if (innerSubscription) { + innerSubscription.unsubscribe(); + } + this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index)); + }; + SwitchMapSubscriber.prototype._complete = function () { + var innerSubscription = this.innerSubscription; + if (!innerSubscription || innerSubscription.closed) { + _super.prototype._complete.call(this); + } + }; + SwitchMapSubscriber.prototype._unsubscribe = function () { + this.innerSubscription = null; + }; + SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) { + this.remove(innerSub); + this.innerSubscription = null; + if (this.isStopped) { + _super.prototype._complete.call(this); + } + }; + SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (this.resultSelector) { + this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex); + } + else { + this.destination.next(innerValue); + } + }; + SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) { + var result; + try { + result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return SwitchMapSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); + +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],199:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError'); +var EmptyObservable_1 = require('../observable/EmptyObservable'); +/** + * Emits only the first `count` values emitted by the source Observable. + * + * Takes the first `count` values from the source, then + * completes. + * + * + * + * `take` returns an Observable that emits only the first `count` values emitted + * by the source Observable. If the source emits fewer than `count` values then + * all of its values are emitted. After that, it completes, regardless if the + * source completes. + * + * @example Take the first 5 seconds of an infinite 1-second interval Observable + * var interval = Rx.Observable.interval(1000); + * var five = interval.take(5); + * five.subscribe(x => console.log(x)); + * + * @see {@link takeLast} + * @see {@link takeUntil} + * @see {@link takeWhile} + * @see {@link skip} + * + * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an + * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`. + * + * @param {number} count The maximum number of `next` values to emit. + * @return {Observable} An Observable that emits only the first `count` + * values emitted by the source Observable, or all of the values from the source + * if the source emits fewer than `count` values. + * @method take + * @owner Observable + */ +function take(count) { + return function (source) { + if (count === 0) { + return new EmptyObservable_1.EmptyObservable(); + } + else { + return source.lift(new TakeOperator(count)); + } + }; +} +exports.take = take; +var TakeOperator = (function () { + function TakeOperator(total) { + this.total = total; + if (this.total < 0) { + throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; + } + } + TakeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeSubscriber(subscriber, this.total)); + }; + return TakeOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var TakeSubscriber = (function (_super) { + __extends(TakeSubscriber, _super); + function TakeSubscriber(destination, total) { + _super.call(this, destination); + this.total = total; + this.count = 0; + } + TakeSubscriber.prototype._next = function (value) { + var total = this.total; + var count = ++this.count; + if (count <= total) { + this.destination.next(value); + if (count === total) { + this.destination.complete(); + this.unsubscribe(); + } + } + }; + return TakeSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36,"../observable/EmptyObservable":96,"../util/ArgumentOutOfRangeError":218}],200:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError'); +var EmptyObservable_1 = require('../observable/EmptyObservable'); +/** + * Emits only the last `count` values emitted by the source Observable. + * + * Remembers the latest `count` values, then emits those + * only when the source completes. + * + * + * + * `takeLast` returns an Observable that emits at most the last `count` values + * emitted by the source Observable. If the source emits fewer than `count` + * values then all of its values are emitted. This operator must wait until the + * `complete` notification emission from the source in order to emit the `next` + * values on the output Observable, because otherwise it is impossible to know + * whether or not more values will be emitted on the source. For this reason, + * all values are emitted synchronously, followed by the complete notification. + * + * @example Take the last 3 values of an Observable with many values + * var many = Rx.Observable.range(1, 100); + * var lastThree = many.takeLast(3); + * lastThree.subscribe(x => console.log(x)); + * + * @see {@link take} + * @see {@link takeUntil} + * @see {@link takeWhile} + * @see {@link skip} + * + * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an + * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`. + * + * @param {number} count The maximum number of values to emit from the end of + * the sequence of values emitted by the source Observable. + * @return {Observable} An Observable that emits at most the last count + * values emitted by the source Observable. + * @method takeLast + * @owner Observable + */ +function takeLast(count) { + return function takeLastOperatorFunction(source) { + if (count === 0) { + return new EmptyObservable_1.EmptyObservable(); + } + else { + return source.lift(new TakeLastOperator(count)); + } + }; +} +exports.takeLast = takeLast; +var TakeLastOperator = (function () { + function TakeLastOperator(total) { + this.total = total; + if (this.total < 0) { + throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; + } + } + TakeLastOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeLastSubscriber(subscriber, this.total)); + }; + return TakeLastOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var TakeLastSubscriber = (function (_super) { + __extends(TakeLastSubscriber, _super); + function TakeLastSubscriber(destination, total) { + _super.call(this, destination); + this.total = total; + this.ring = new Array(); + this.count = 0; + } + TakeLastSubscriber.prototype._next = function (value) { + var ring = this.ring; + var total = this.total; + var count = this.count++; + if (ring.length < total) { + ring.push(value); + } + else { + var index = count % total; + ring[index] = value; + } + }; + TakeLastSubscriber.prototype._complete = function () { + var destination = this.destination; + var count = this.count; + if (count > 0) { + var total = this.count >= this.total ? this.total : this.count; + var ring = this.ring; + for (var i = 0; i < total; i++) { + var idx = (count++) % total; + destination.next(ring[idx]); + } + } + destination.complete(); + }; + return TakeLastSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36,"../observable/EmptyObservable":96,"../util/ArgumentOutOfRangeError":218}],201:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/** + * Emits the values emitted by the source Observable until a `notifier` + * Observable emits a value. + * + * Lets values pass until a second Observable, + * `notifier`, emits something. Then, it completes. + * + * + * + * `takeUntil` subscribes and begins mirroring the source Observable. It also + * monitors a second Observable, `notifier` that you provide. If the `notifier` + * emits a value or a complete notification, the output Observable stops + * mirroring the source Observable and completes. + * + * @example Tick every second until the first click happens + * var interval = Rx.Observable.interval(1000); + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = interval.takeUntil(clicks); + * result.subscribe(x => console.log(x)); + * + * @see {@link take} + * @see {@link takeLast} + * @see {@link takeWhile} + * @see {@link skip} + * + * @param {Observable} notifier The Observable whose first emitted value will + * cause the output Observable of `takeUntil` to stop emitting values from the + * source Observable. + * @return {Observable} An Observable that emits the values from the source + * Observable until such time as `notifier` emits its first value. + * @method takeUntil + * @owner Observable + */ +function takeUntil(notifier) { + return function (source) { return source.lift(new TakeUntilOperator(notifier)); }; +} +exports.takeUntil = takeUntil; +var TakeUntilOperator = (function () { + function TakeUntilOperator(notifier) { + this.notifier = notifier; + } + TakeUntilOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier)); + }; + return TakeUntilOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var TakeUntilSubscriber = (function (_super) { + __extends(TakeUntilSubscriber, _super); + function TakeUntilSubscriber(destination, notifier) { + _super.call(this, destination); + this.notifier = notifier; + this.add(subscribeToResult_1.subscribeToResult(this, notifier)); + } + TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.complete(); + }; + TakeUntilSubscriber.prototype.notifyComplete = function () { + // noop + }; + return TakeUntilSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); + +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],202:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/** + * Emits values emitted by the source Observable so long as each value satisfies + * the given `predicate`, and then completes as soon as this `predicate` is not + * satisfied. + * + * Takes values from the source only while they pass the + * condition given. When the first value does not satisfy, it completes. + * + * + * + * `takeWhile` subscribes and begins mirroring the source Observable. Each value + * emitted on the source is given to the `predicate` function which returns a + * boolean, representing a condition to be satisfied by the source values. The + * output Observable emits the source values until such time as the `predicate` + * returns false, at which point `takeWhile` stops mirroring the source + * Observable and completes the output Observable. + * + * @example Emit click events only while the clientX property is greater than 200 + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var result = clicks.takeWhile(ev => ev.clientX > 200); + * result.subscribe(x => console.log(x)); + * + * @see {@link take} + * @see {@link takeLast} + * @see {@link takeUntil} + * @see {@link skip} + * + * @param {function(value: T, index: number): boolean} predicate A function that + * evaluates a value emitted by the source Observable and returns a boolean. + * Also takes the (zero-based) index as the second argument. + * @return {Observable} An Observable that emits the values from the source + * Observable so long as each value satisfies the condition defined by the + * `predicate`, then completes. + * @method takeWhile + * @owner Observable + */ +function takeWhile(predicate) { + return function (source) { return source.lift(new TakeWhileOperator(predicate)); }; +} +exports.takeWhile = takeWhile; +var TakeWhileOperator = (function () { + function TakeWhileOperator(predicate) { + this.predicate = predicate; + } + TakeWhileOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate)); + }; + return TakeWhileOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var TakeWhileSubscriber = (function (_super) { + __extends(TakeWhileSubscriber, _super); + function TakeWhileSubscriber(destination, predicate) { + _super.call(this, destination); + this.predicate = predicate; + this.index = 0; + } + TakeWhileSubscriber.prototype._next = function (value) { + var destination = this.destination; + var result; + try { + result = this.predicate(value, this.index++); + } + catch (err) { + destination.error(err); + return; + } + this.nextOrComplete(value, result); + }; + TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) { + var destination = this.destination; + if (Boolean(predicateResult)) { + destination.next(value); + } + else { + destination.complete(); + } + }; + return TakeWhileSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],203:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscriber_1 = require('../Subscriber'); +/* tslint:enable:max-line-length */ +/** + * Perform a side effect for every emission on the source Observable, but return + * an Observable that is identical to the source. + * + * Intercepts each emission on the source and runs a + * function, but returns an output which is identical to the source as long as errors don't occur. + * + * + * + * Returns a mirrored Observable of the source Observable, but modified so that + * the provided Observer is called to perform a side effect for every value, + * error, and completion emitted by the source. Any errors that are thrown in + * the aforementioned Observer or handlers are safely sent down the error path + * of the output Observable. + * + * This operator is useful for debugging your Observables for the correct values + * or performing other side effects. + * + * Note: this is different to a `subscribe` on the Observable. If the Observable + * returned by `do` is not subscribed, the side effects specified by the + * Observer will never happen. `do` therefore simply spies on existing + * execution, it does not trigger an execution to happen like `subscribe` does. + * + * @example Map every click to the clientX position of that click, while also logging the click event + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var positions = clicks + * .do(ev => console.log(ev)) + * .map(ev => ev.clientX); + * positions.subscribe(x => console.log(x)); + * + * @see {@link map} + * @see {@link subscribe} + * + * @param {Observer|function} [nextOrObserver] A normal Observer object or a + * callback for `next`. + * @param {function} [error] Callback for errors in the source. + * @param {function} [complete] Callback for the completion of the source. + * @return {Observable} An Observable identical to the source, but runs the + * specified Observer or callback(s) for each item. + * @name tap + */ +function tap(nextOrObserver, error, complete) { + return function tapOperatorFunction(source) { + return source.lift(new DoOperator(nextOrObserver, error, complete)); + }; +} +exports.tap = tap; +var DoOperator = (function () { + function DoOperator(nextOrObserver, error, complete) { + this.nextOrObserver = nextOrObserver; + this.error = error; + this.complete = complete; + } + DoOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); + }; + return DoOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var DoSubscriber = (function (_super) { + __extends(DoSubscriber, _super); + function DoSubscriber(destination, nextOrObserver, error, complete) { + _super.call(this, destination); + var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete); + safeSubscriber.syncErrorThrowable = true; + this.add(safeSubscriber); + this.safeSubscriber = safeSubscriber; + } + DoSubscriber.prototype._next = function (value) { + var safeSubscriber = this.safeSubscriber; + safeSubscriber.next(value); + if (safeSubscriber.syncErrorThrown) { + this.destination.error(safeSubscriber.syncErrorValue); + } + else { + this.destination.next(value); + } + }; + DoSubscriber.prototype._error = function (err) { + var safeSubscriber = this.safeSubscriber; + safeSubscriber.error(err); + if (safeSubscriber.syncErrorThrown) { + this.destination.error(safeSubscriber.syncErrorValue); + } + else { + this.destination.error(err); + } + }; + DoSubscriber.prototype._complete = function () { + var safeSubscriber = this.safeSubscriber; + safeSubscriber.complete(); + if (safeSubscriber.syncErrorThrown) { + this.destination.error(safeSubscriber.syncErrorValue); + } + else { + this.destination.complete(); + } + }; + return DoSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36}],204:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var async_1 = require('../scheduler/async'); +var isDate_1 = require('../util/isDate'); +var Subscriber_1 = require('../Subscriber'); +var TimeoutError_1 = require('../util/TimeoutError'); +/** + * + * Errors if Observable does not emit a value in given time span. + * + * Timeouts on Observable that doesn't emit values fast enough. + * + * + * + * `timeout` operator accepts as an argument either a number or a Date. + * + * If number was provided, it returns an Observable that behaves like a source + * Observable, unless there is a period of time where there is no value emitted. + * So if you provide `100` as argument and first value comes after 50ms from + * the moment of subscription, this value will be simply re-emitted by the resulting + * Observable. If however after that 100ms passes without a second value being emitted, + * stream will end with an error and source Observable will be unsubscribed. + * These checks are performed throughout whole lifecycle of Observable - from the moment + * it was subscribed to, until it completes or errors itself. Thus every value must be + * emitted within specified period since previous value. + * + * If provided argument was Date, returned Observable behaves differently. It throws + * if Observable did not complete before provided Date. This means that periods between + * emission of particular values do not matter in this case. If Observable did not complete + * before provided Date, source Observable will be unsubscribed. Other than that, resulting + * stream behaves just as source Observable. + * + * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments) + * when returned Observable will check if source stream emitted value or completed. + * + * @example Check if ticks are emitted within certain timespan + * const seconds = Rx.Observable.interval(1000); + * + * seconds.timeout(1100) // Let's use bigger timespan to be safe, + * // since `interval` might fire a bit later then scheduled. + * .subscribe( + * value => console.log(value), // Will emit numbers just as regular `interval` would. + * err => console.log(err) // Will never be called. + * ); + * + * seconds.timeout(900).subscribe( + * value => console.log(value), // Will never be called. + * err => console.log(err) // Will emit error before even first value is emitted, + * // since it did not arrive within 900ms period. + * ); + * + * @example Use Date to check if Observable completed + * const seconds = Rx.Observable.interval(1000); + * + * seconds.timeout(new Date("December 17, 2020 03:24:00")) + * .subscribe( + * value => console.log(value), // Will emit values as regular `interval` would + * // until December 17, 2020 at 03:24:00. + * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error, + * // since Observable did not complete by then. + * ); + * + * @see {@link timeoutWith} + * + * @param {number|Date} due Number specifying period within which Observable must emit values + * or Date specifying before when Observable should complete + * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur. + * @return {Observable} Observable that mirrors behaviour of source, unless timeout checks fail. + * @method timeout + * @owner Observable + */ +function timeout(due, scheduler) { + if (scheduler === void 0) { scheduler = async_1.async; } + var absoluteTimeout = isDate_1.isDate(due); + var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); + return function (source) { return source.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new TimeoutError_1.TimeoutError())); }; +} +exports.timeout = timeout; +var TimeoutOperator = (function () { + function TimeoutOperator(waitFor, absoluteTimeout, scheduler, errorInstance) { + this.waitFor = waitFor; + this.absoluteTimeout = absoluteTimeout; + this.scheduler = scheduler; + this.errorInstance = errorInstance; + } + TimeoutOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.scheduler, this.errorInstance)); + }; + return TimeoutOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var TimeoutSubscriber = (function (_super) { + __extends(TimeoutSubscriber, _super); + function TimeoutSubscriber(destination, absoluteTimeout, waitFor, scheduler, errorInstance) { + _super.call(this, destination); + this.absoluteTimeout = absoluteTimeout; + this.waitFor = waitFor; + this.scheduler = scheduler; + this.errorInstance = errorInstance; + this.action = null; + this.scheduleTimeout(); + } + TimeoutSubscriber.dispatchTimeout = function (subscriber) { + subscriber.error(subscriber.errorInstance); + }; + TimeoutSubscriber.prototype.scheduleTimeout = function () { + var action = this.action; + if (action) { + // Recycle the action if we've already scheduled one. All the production + // Scheduler Actions mutate their state/delay time and return themeselves. + // VirtualActions are immutable, so they create and return a clone. In this + // case, we need to set the action reference to the most recent VirtualAction, + // to ensure that's the one we clone from next time. + this.action = action.schedule(this, this.waitFor); + } + else { + this.add(this.action = this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, this)); + } + }; + TimeoutSubscriber.prototype._next = function (value) { + if (!this.absoluteTimeout) { + this.scheduleTimeout(); + } + _super.prototype._next.call(this, value); + }; + TimeoutSubscriber.prototype._unsubscribe = function () { + this.action = null; + this.scheduler = null; + this.errorInstance = null; + }; + return TimeoutSubscriber; +}(Subscriber_1.Subscriber)); + +},{"../Subscriber":36,"../scheduler/async":212,"../util/TimeoutError":222,"../util/isDate":228}],205:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +/* tslint:enable:max-line-length */ +/** + * Combines the source Observable with other Observables to create an Observable + * whose values are calculated from the latest values of each, only when the + * source emits. + * + * Whenever the source Observable emits a value, it + * computes a formula using that value plus the latest values from other input + * Observables, then emits the output of that formula. + * + * + * + * `withLatestFrom` combines each value from the source Observable (the + * instance) with the latest values from the other input Observables only when + * the source emits a value, optionally using a `project` function to determine + * the value to be emitted on the output Observable. All input Observables must + * emit at least one value before the output Observable will emit a value. + * + * @example On every click event, emit an array with the latest timer event plus the click event + * var clicks = Rx.Observable.fromEvent(document, 'click'); + * var timer = Rx.Observable.interval(1000); + * var result = clicks.withLatestFrom(timer); + * result.subscribe(x => console.log(x)); + * + * @see {@link combineLatest} + * + * @param {ObservableInput} other An input Observable to combine with the source + * Observable. More than one input Observables may be given as argument. + * @param {Function} [project] Projection function for combining values + * together. Receives all values in order of the Observables passed, where the + * first parameter is a value from the source Observable. (e.g. + * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not + * passed, arrays will be emitted on the output Observable. + * @return {Observable} An Observable of projected values from the most recent + * values from each input Observable, or an array of the most recent values from + * each input Observable. + * @method withLatestFrom + * @owner Observable + */ +function withLatestFrom() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + return function (source) { + var project; + if (typeof args[args.length - 1] === 'function') { + project = args.pop(); + } + var observables = args; + return source.lift(new WithLatestFromOperator(observables, project)); + }; +} +exports.withLatestFrom = withLatestFrom; +var WithLatestFromOperator = (function () { + function WithLatestFromOperator(observables, project) { + this.observables = observables; + this.project = project; + } + WithLatestFromOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project)); + }; + return WithLatestFromOperator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var WithLatestFromSubscriber = (function (_super) { + __extends(WithLatestFromSubscriber, _super); + function WithLatestFromSubscriber(destination, observables, project) { + _super.call(this, destination); + this.observables = observables; + this.project = project; + this.toRespond = []; + var len = observables.length; + this.values = new Array(len); + for (var i = 0; i < len; i++) { + this.toRespond.push(i); + } + for (var i = 0; i < len; i++) { + var observable = observables[i]; + this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i)); + } + } + WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.values[outerIndex] = innerValue; + var toRespond = this.toRespond; + if (toRespond.length > 0) { + var found = toRespond.indexOf(outerIndex); + if (found !== -1) { + toRespond.splice(found, 1); + } + } + }; + WithLatestFromSubscriber.prototype.notifyComplete = function () { + // noop + }; + WithLatestFromSubscriber.prototype._next = function (value) { + if (this.toRespond.length === 0) { + var args = [value].concat(this.values); + if (this.project) { + this._tryProject(args); + } + else { + this.destination.next(args); + } + } + }; + WithLatestFromSubscriber.prototype._tryProject = function (args) { + var result; + try { + result = this.project.apply(this, args); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return WithLatestFromSubscriber; +}(OuterSubscriber_1.OuterSubscriber)); + +},{"../OuterSubscriber":31,"../util/subscribeToResult":237}],206:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var ArrayObservable_1 = require('../observable/ArrayObservable'); +var isArray_1 = require('../util/isArray'); +var Subscriber_1 = require('../Subscriber'); +var OuterSubscriber_1 = require('../OuterSubscriber'); +var subscribeToResult_1 = require('../util/subscribeToResult'); +var iterator_1 = require('../symbol/iterator'); +/* tslint:enable:max-line-length */ +/** + * @param observables + * @return {Observable} + * @method zip + * @owner Observable + */ +function zip() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + return function zipOperatorFunction(source) { + return source.lift.call(zipStatic.apply(void 0, [source].concat(observables))); + }; +} +exports.zip = zip; +/* tslint:enable:max-line-length */ +/** + * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each + * of its input Observables. + * + * If the latest parameter is a function, this function is used to compute the created value from the input values. + * Otherwise, an array of the input values is returned. + * + * @example Combine age and name from different sources + * + * let age$ = Observable.of(27, 25, 29); + * let name$ = Observable.of('Foo', 'Bar', 'Beer'); + * let isDev$ = Observable.of(true, true, false); + * + * Observable + * .zip(age$, + * name$, + * isDev$, + * (age: number, name: string, isDev: boolean) => ({ age, name, isDev })) + * .subscribe(x => console.log(x)); + * + * // outputs + * // { age: 27, name: 'Foo', isDev: true } + * // { age: 25, name: 'Bar', isDev: true } + * // { age: 29, name: 'Beer', isDev: false } + * + * @param observables + * @return {Observable} + * @static true + * @name zip + * @owner Observable + */ +function zipStatic() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var project = observables[observables.length - 1]; + if (typeof project === 'function') { + observables.pop(); + } + return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project)); +} +exports.zipStatic = zipStatic; +var ZipOperator = (function () { + function ZipOperator(project) { + this.project = project; + } + ZipOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ZipSubscriber(subscriber, this.project)); + }; + return ZipOperator; +}()); +exports.ZipOperator = ZipOperator; +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var ZipSubscriber = (function (_super) { + __extends(ZipSubscriber, _super); + function ZipSubscriber(destination, project, values) { + if (values === void 0) { values = Object.create(null); } + _super.call(this, destination); + this.iterators = []; + this.active = 0; + this.project = (typeof project === 'function') ? project : null; + this.values = values; + } + ZipSubscriber.prototype._next = function (value) { + var iterators = this.iterators; + if (isArray_1.isArray(value)) { + iterators.push(new StaticArrayIterator(value)); + } + else if (typeof value[iterator_1.iterator] === 'function') { + iterators.push(new StaticIterator(value[iterator_1.iterator]())); + } + else { + iterators.push(new ZipBufferIterator(this.destination, this, value)); + } + }; + ZipSubscriber.prototype._complete = function () { + var iterators = this.iterators; + var len = iterators.length; + if (len === 0) { + this.destination.complete(); + return; + } + this.active = len; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (iterator.stillUnsubscribed) { + this.add(iterator.subscribe(iterator, i)); + } + else { + this.active--; // not an observable + } + } + }; + ZipSubscriber.prototype.notifyInactive = function () { + this.active--; + if (this.active === 0) { + this.destination.complete(); + } + }; + ZipSubscriber.prototype.checkIterators = function () { + var iterators = this.iterators; + var len = iterators.length; + var destination = this.destination; + // abort if not all of them have values + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { + return; + } + } + var shouldComplete = false; + var args = []; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + var result = iterator.next(); + // check to see if it's completed now that you've gotten + // the next value. + if (iterator.hasCompleted()) { + shouldComplete = true; + } + if (result.done) { + destination.complete(); + return; + } + args.push(result.value); + } + if (this.project) { + this._tryProject(args); + } + else { + destination.next(args); + } + if (shouldComplete) { + destination.complete(); + } + }; + ZipSubscriber.prototype._tryProject = function (args) { + var result; + try { + result = this.project.apply(this, args); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return ZipSubscriber; +}(Subscriber_1.Subscriber)); +exports.ZipSubscriber = ZipSubscriber; +var StaticIterator = (function () { + function StaticIterator(iterator) { + this.iterator = iterator; + this.nextResult = iterator.next(); + } + StaticIterator.prototype.hasValue = function () { + return true; + }; + StaticIterator.prototype.next = function () { + var result = this.nextResult; + this.nextResult = this.iterator.next(); + return result; + }; + StaticIterator.prototype.hasCompleted = function () { + var nextResult = this.nextResult; + return nextResult && nextResult.done; + }; + return StaticIterator; +}()); +var StaticArrayIterator = (function () { + function StaticArrayIterator(array) { + this.array = array; + this.index = 0; + this.length = 0; + this.length = array.length; + } + StaticArrayIterator.prototype[iterator_1.iterator] = function () { + return this; + }; + StaticArrayIterator.prototype.next = function (value) { + var i = this.index++; + var array = this.array; + return i < this.length ? { value: array[i], done: false } : { value: null, done: true }; + }; + StaticArrayIterator.prototype.hasValue = function () { + return this.array.length > this.index; + }; + StaticArrayIterator.prototype.hasCompleted = function () { + return this.array.length === this.index; + }; + return StaticArrayIterator; +}()); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var ZipBufferIterator = (function (_super) { + __extends(ZipBufferIterator, _super); + function ZipBufferIterator(destination, parent, observable) { + _super.call(this, destination); + this.parent = parent; + this.observable = observable; + this.stillUnsubscribed = true; + this.buffer = []; + this.isComplete = false; + } + ZipBufferIterator.prototype[iterator_1.iterator] = function () { + return this; + }; + // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next + // this is legit because `next()` will never be called by a subscription in this case. + ZipBufferIterator.prototype.next = function () { + var buffer = this.buffer; + if (buffer.length === 0 && this.isComplete) { + return { value: null, done: true }; + } + else { + return { value: buffer.shift(), done: false }; + } + }; + ZipBufferIterator.prototype.hasValue = function () { + return this.buffer.length > 0; + }; + ZipBufferIterator.prototype.hasCompleted = function () { + return this.buffer.length === 0 && this.isComplete; + }; + ZipBufferIterator.prototype.notifyComplete = function () { + if (this.buffer.length > 0) { + this.isComplete = true; + this.parent.notifyInactive(); + } + else { + this.destination.complete(); + } + }; + ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.buffer.push(innerValue); + this.parent.checkIterators(); + }; + ZipBufferIterator.prototype.subscribe = function (value, index) { + return subscribeToResult_1.subscribeToResult(this, this.observable, this, index); + }; + return ZipBufferIterator; +}(OuterSubscriber_1.OuterSubscriber)); + +},{"../OuterSubscriber":31,"../Subscriber":36,"../observable/ArrayObservable":93,"../symbol/iterator":214,"../util/isArray":226,"../util/subscribeToResult":237}],207:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Subscription_1 = require('../Subscription'); +/** + * A unit of work to be executed in a {@link Scheduler}. An action is typically + * created from within a Scheduler and an RxJS user does not need to concern + * themselves about creating and manipulating an Action. + * + * ```ts + * class Action extends Subscription { + * new (scheduler: Scheduler, work: (state?: T) => void); + * schedule(state?: T, delay: number = 0): Subscription; + * } + * ``` + * + * @class Action + */ +var Action = (function (_super) { + __extends(Action, _super); + function Action(scheduler, work) { + _super.call(this); + } + /** + * Schedules this action on its parent Scheduler for execution. May be passed + * some context object, `state`. May happen at some point in the future, + * according to the `delay` parameter, if specified. + * @param {T} [state] Some contextual data that the `work` function uses when + * called by the Scheduler. + * @param {number} [delay] Time to wait before executing the work, where the + * time unit is implicit and defined by the Scheduler. + * @return {void} + */ + Action.prototype.schedule = function (state, delay) { + if (delay === void 0) { delay = 0; } + return this; + }; + return Action; +}(Subscription_1.Subscription)); +exports.Action = Action; + +},{"../Subscription":37}],208:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var root_1 = require('../util/root'); +var Action_1 = require('./Action'); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var AsyncAction = (function (_super) { + __extends(AsyncAction, _super); + function AsyncAction(scheduler, work) { + _super.call(this, scheduler, work); + this.scheduler = scheduler; + this.work = work; + this.pending = false; + } + AsyncAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { delay = 0; } + if (this.closed) { + return this; + } + // Always replace the current state with the new state. + this.state = state; + // Set the pending flag indicating that this action has been scheduled, or + // has recursively rescheduled itself. + this.pending = true; + var id = this.id; + var scheduler = this.scheduler; + // + // Important implementation note: + // + // Actions only execute once by default, unless rescheduled from within the + // scheduled callback. This allows us to implement single and repeat + // actions via the same code path, without adding API surface area, as well + // as mimic traditional recursion but across asynchronous boundaries. + // + // However, JS runtimes and timers distinguish between intervals achieved by + // serial `setTimeout` calls vs. a single `setInterval` call. An interval of + // serial `setTimeout` calls can be individually delayed, which delays + // scheduling the next `setTimeout`, and so on. `setInterval` attempts to + // guarantee the interval callback will be invoked more precisely to the + // interval period, regardless of load. + // + // Therefore, we use `setInterval` to schedule single and repeat actions. + // If the action reschedules itself with the same delay, the interval is not + // canceled. If the action doesn't reschedule, or reschedules with a + // different delay, the interval will be canceled after scheduled callback + // execution. + // + if (id != null) { + this.id = this.recycleAsyncId(scheduler, id, delay); + } + this.delay = delay; + // If this action has already an async Id, don't request a new one. + this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); + return this; + }; + AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { delay = 0; } + return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay); + }; + AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { delay = 0; } + // If this action is rescheduled with the same delay time, don't clear the interval id. + if (delay !== null && this.delay === delay && this.pending === false) { + return id; + } + // Otherwise, if the action's delay time is different from the current delay, + // or the action has been rescheduled before it's executed, clear the interval id + return root_1.root.clearInterval(id) && undefined || undefined; + }; + /** + * Immediately executes this action and the `work` it contains. + * @return {any} + */ + AsyncAction.prototype.execute = function (state, delay) { + if (this.closed) { + return new Error('executing a cancelled action'); + } + this.pending = false; + var error = this._execute(state, delay); + if (error) { + return error; + } + else if (this.pending === false && this.id != null) { + // Dequeue if the action didn't reschedule itself. Don't call + // unsubscribe(), because the action could reschedule later. + // For example: + // ``` + // scheduler.schedule(function doWork(counter) { + // /* ... I'm a busy worker bee ... */ + // var originalAction = this; + // /* wait 100ms before rescheduling the action */ + // setTimeout(function () { + // originalAction.schedule(counter + 1); + // }, 100); + // }, 1000); + // ``` + this.id = this.recycleAsyncId(this.scheduler, this.id, null); + } + }; + AsyncAction.prototype._execute = function (state, delay) { + var errored = false; + var errorValue = undefined; + try { + this.work(state); + } + catch (e) { + errored = true; + errorValue = !!e && e || new Error(e); + } + if (errored) { + this.unsubscribe(); + return errorValue; + } + }; + AsyncAction.prototype._unsubscribe = function () { + var id = this.id; + var scheduler = this.scheduler; + var actions = scheduler.actions; + var index = actions.indexOf(this); + this.work = null; + this.state = null; + this.pending = false; + this.scheduler = null; + if (index !== -1) { + actions.splice(index, 1); + } + if (id != null) { + this.id = this.recycleAsyncId(scheduler, id, null); + } + this.delay = null; + }; + return AsyncAction; +}(Action_1.Action)); +exports.AsyncAction = AsyncAction; + +},{"../util/root":236,"./Action":207}],209:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Scheduler_1 = require('../Scheduler'); +var AsyncScheduler = (function (_super) { + __extends(AsyncScheduler, _super); + function AsyncScheduler() { + _super.apply(this, arguments); + this.actions = []; + /** + * A flag to indicate whether the Scheduler is currently executing a batch of + * queued actions. + * @type {boolean} + */ + this.active = false; + /** + * An internal ID used to track the latest asynchronous task such as those + * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and + * others. + * @type {any} + */ + this.scheduled = undefined; + } + AsyncScheduler.prototype.flush = function (action) { + var actions = this.actions; + if (this.active) { + actions.push(action); + return; + } + var error; + this.active = true; + do { + if (error = action.execute(action.state, action.delay)) { + break; + } + } while (action = actions.shift()); // exhaust the scheduler queue + this.active = false; + if (error) { + while (action = actions.shift()) { + action.unsubscribe(); + } + throw error; + } + }; + return AsyncScheduler; +}(Scheduler_1.Scheduler)); +exports.AsyncScheduler = AsyncScheduler; + +},{"../Scheduler":33}],210:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var AsyncAction_1 = require('./AsyncAction'); +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +var QueueAction = (function (_super) { + __extends(QueueAction, _super); + function QueueAction(scheduler, work) { + _super.call(this, scheduler, work); + this.scheduler = scheduler; + this.work = work; + } + QueueAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { delay = 0; } + if (delay > 0) { + return _super.prototype.schedule.call(this, state, delay); + } + this.delay = delay; + this.state = state; + this.scheduler.flush(this); + return this; + }; + QueueAction.prototype.execute = function (state, delay) { + return (delay > 0 || this.closed) ? + _super.prototype.execute.call(this, state, delay) : + this._execute(state, delay); + }; + QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { delay = 0; } + // If delay exists and is greater than 0, or if the delay is null (the + // action wasn't rescheduled) but was originally scheduled as an async + // action, then recycle as an async action. + if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { + return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); + } + // Otherwise flush the scheduler starting with this action. + return scheduler.flush(this); + }; + return QueueAction; +}(AsyncAction_1.AsyncAction)); +exports.QueueAction = QueueAction; + +},{"./AsyncAction":208}],211:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var AsyncScheduler_1 = require('./AsyncScheduler'); +var QueueScheduler = (function (_super) { + __extends(QueueScheduler, _super); + function QueueScheduler() { + _super.apply(this, arguments); + } + return QueueScheduler; +}(AsyncScheduler_1.AsyncScheduler)); +exports.QueueScheduler = QueueScheduler; + +},{"./AsyncScheduler":209}],212:[function(require,module,exports){ +"use strict"; +var AsyncAction_1 = require('./AsyncAction'); +var AsyncScheduler_1 = require('./AsyncScheduler'); +/** + * + * Async Scheduler + * + * Schedule task as if you used setTimeout(task, duration) + * + * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript + * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating + * in intervals. + * + * If you just want to "defer" task, that is to perform it right after currently + * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`), + * better choice will be the {@link asap} scheduler. + * + * @example Use async scheduler to delay task + * const task = () => console.log('it works!'); + * + * Rx.Scheduler.async.schedule(task, 2000); + * + * // After 2 seconds logs: + * // "it works!" + * + * + * @example Use async scheduler to repeat task in intervals + * function task(state) { + * console.log(state); + * this.schedule(state + 1, 1000); // `this` references currently executing Action, + * // which we reschedule with new state and delay + * } + * + * Rx.Scheduler.async.schedule(task, 3000, 0); + * + * // Logs: + * // 0 after 3s + * // 1 after 4s + * // 2 after 5s + * // 3 after 6s + * + * @static true + * @name async + * @owner Scheduler + */ +exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction); + +},{"./AsyncAction":208,"./AsyncScheduler":209}],213:[function(require,module,exports){ +"use strict"; +var QueueAction_1 = require('./QueueAction'); +var QueueScheduler_1 = require('./QueueScheduler'); +/** + * + * Queue Scheduler + * + * Put every next task on a queue, instead of executing it immediately + * + * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler. + * + * When used without delay, it schedules given task synchronously - executes it right when + * it is scheduled. However when called recursively, that is when inside the scheduled task, + * another task is scheduled with queue scheduler, instead of executing immediately as well, + * that task will be put on a queue and wait for current one to finish. + * + * This means that when you execute task with `queue` scheduler, you are sure it will end + * before any other task scheduled with that scheduler will start. + * + * @examples Schedule recursively first, then do something + * + * Rx.Scheduler.queue.schedule(() => { + * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue + * + * console.log('first'); + * }); + * + * // Logs: + * // "first" + * // "second" + * + * + * @example Reschedule itself recursively + * + * Rx.Scheduler.queue.schedule(function(state) { + * if (state !== 0) { + * console.log('before', state); + * this.schedule(state - 1); // `this` references currently executing Action, + * // which we reschedule with new state + * console.log('after', state); + * } + * }, 0, 3); + * + * // In scheduler that runs recursively, you would expect: + * // "before", 3 + * // "before", 2 + * // "before", 1 + * // "after", 1 + * // "after", 2 + * // "after", 3 + * + * // But with queue it logs: + * // "before", 3 + * // "after", 3 + * // "before", 2 + * // "after", 2 + * // "before", 1 + * // "after", 1 + * + * + * @static true + * @name queue + * @owner Scheduler + */ +exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction); + +},{"./QueueAction":210,"./QueueScheduler":211}],214:[function(require,module,exports){ +"use strict"; +var root_1 = require('../util/root'); +function symbolIteratorPonyfill(root) { + var Symbol = root.Symbol; + if (typeof Symbol === 'function') { + if (!Symbol.iterator) { + Symbol.iterator = Symbol('iterator polyfill'); + } + return Symbol.iterator; + } + else { + // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC) + var Set_1 = root.Set; + if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') { + return '@@iterator'; + } + var Map_1 = root.Map; + // required for compatability with es6-shim + if (Map_1) { + var keys = Object.getOwnPropertyNames(Map_1.prototype); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal. + if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) { + return key; + } + } + } + return '@@iterator'; + } +} +exports.symbolIteratorPonyfill = symbolIteratorPonyfill; +exports.iterator = symbolIteratorPonyfill(root_1.root); +/** + * @deprecated use iterator instead + */ +exports.$$iterator = exports.iterator; + +},{"../util/root":236}],215:[function(require,module,exports){ +"use strict"; +var root_1 = require('../util/root'); +function getSymbolObservable(context) { + var $$observable; + var Symbol = context.Symbol; + if (typeof Symbol === 'function') { + if (Symbol.observable) { + $$observable = Symbol.observable; + } + else { + $$observable = Symbol('observable'); + Symbol.observable = $$observable; + } + } + else { + $$observable = '@@observable'; + } + return $$observable; +} +exports.getSymbolObservable = getSymbolObservable; +exports.observable = getSymbolObservable(root_1.root); +/** + * @deprecated use observable instead + */ +exports.$$observable = exports.observable; + +},{"../util/root":236}],216:[function(require,module,exports){ +"use strict"; +var root_1 = require('../util/root'); +var Symbol = root_1.root.Symbol; +exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ? + Symbol.for('rxSubscriber') : '@@rxSubscriber'; +/** + * @deprecated use rxSubscriber instead + */ +exports.$$rxSubscriber = exports.rxSubscriber; + +},{"../util/root":236}],217:[function(require,module,exports){ +"use strict"; +var root_1 = require('./root'); +var RequestAnimationFrameDefinition = (function () { + function RequestAnimationFrameDefinition(root) { + if (root.requestAnimationFrame) { + this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root); + this.requestAnimationFrame = root.requestAnimationFrame.bind(root); + } + else if (root.mozRequestAnimationFrame) { + this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root); + this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root); + } + else if (root.webkitRequestAnimationFrame) { + this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root); + this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root); + } + else if (root.msRequestAnimationFrame) { + this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root); + this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root); + } + else if (root.oRequestAnimationFrame) { + this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root); + this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root); + } + else { + this.cancelAnimationFrame = root.clearTimeout.bind(root); + this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); }; + } + } + return RequestAnimationFrameDefinition; +}()); +exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition; +exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root); + +},{"./root":236}],218:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/** + * An error thrown when an element was queried at a certain index of an + * Observable, but no such index or position exists in that sequence. + * + * @see {@link elementAt} + * @see {@link take} + * @see {@link takeLast} + * + * @class ArgumentOutOfRangeError + */ +var ArgumentOutOfRangeError = (function (_super) { + __extends(ArgumentOutOfRangeError, _super); + function ArgumentOutOfRangeError() { + var err = _super.call(this, 'argument out of range'); + this.name = err.name = 'ArgumentOutOfRangeError'; + this.stack = err.stack; + this.message = err.message; + } + return ArgumentOutOfRangeError; +}(Error)); +exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError; + +},{}],219:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/** + * An error thrown when an Observable or a sequence was queried but has no + * elements. + * + * @see {@link first} + * @see {@link last} + * @see {@link single} + * + * @class EmptyError + */ +var EmptyError = (function (_super) { + __extends(EmptyError, _super); + function EmptyError() { + var err = _super.call(this, 'no elements in sequence'); + this.name = err.name = 'EmptyError'; + this.stack = err.stack; + this.message = err.message; + } + return EmptyError; +}(Error)); +exports.EmptyError = EmptyError; + +},{}],220:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/** + * An error thrown when an action is invalid because the object has been + * unsubscribed. + * + * @see {@link Subject} + * @see {@link BehaviorSubject} + * + * @class ObjectUnsubscribedError + */ +var ObjectUnsubscribedError = (function (_super) { + __extends(ObjectUnsubscribedError, _super); + function ObjectUnsubscribedError() { + var err = _super.call(this, 'object unsubscribed'); + this.name = err.name = 'ObjectUnsubscribedError'; + this.stack = err.stack; + this.message = err.message; + } + return ObjectUnsubscribedError; +}(Error)); +exports.ObjectUnsubscribedError = ObjectUnsubscribedError; + +},{}],221:[function(require,module,exports){ +"use strict"; +var root_1 = require('./root'); +function minimalSetImpl() { + // THIS IS NOT a full impl of Set, this is just the minimum + // bits of functionality we need for this library. + return (function () { + function MinimalSet() { + this._values = []; + } + MinimalSet.prototype.add = function (value) { + if (!this.has(value)) { + this._values.push(value); + } + }; + MinimalSet.prototype.has = function (value) { + return this._values.indexOf(value) !== -1; + }; + Object.defineProperty(MinimalSet.prototype, "size", { + get: function () { + return this._values.length; + }, + enumerable: true, + configurable: true + }); + MinimalSet.prototype.clear = function () { + this._values.length = 0; + }; + return MinimalSet; + }()); +} +exports.minimalSetImpl = minimalSetImpl; +exports.Set = root_1.root.Set || minimalSetImpl(); + +},{"./root":236}],222:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/** + * An error thrown when duetime elapses. + * + * @see {@link timeout} + * + * @class TimeoutError + */ +var TimeoutError = (function (_super) { + __extends(TimeoutError, _super); + function TimeoutError() { + var err = _super.call(this, 'Timeout has occurred'); + this.name = err.name = 'TimeoutError'; + this.stack = err.stack; + this.message = err.message; + } + return TimeoutError; +}(Error)); +exports.TimeoutError = TimeoutError; + +},{}],223:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/** + * An error thrown when one or more errors have occurred during the + * `unsubscribe` of a {@link Subscription}. + */ +var UnsubscriptionError = (function (_super) { + __extends(UnsubscriptionError, _super); + function UnsubscriptionError(errors) { + _super.call(this); + this.errors = errors; + var err = Error.call(this, errors ? + errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : ''); + this.name = err.name = 'UnsubscriptionError'; + this.stack = err.stack; + this.message = err.message; + } + return UnsubscriptionError; +}(Error)); +exports.UnsubscriptionError = UnsubscriptionError; + +},{}],224:[function(require,module,exports){ +"use strict"; +// typeof any so that it we don't have to cast when comparing a result to the error object +exports.errorObject = { e: {} }; + +},{}],225:[function(require,module,exports){ +"use strict"; +function identity(x) { + return x; +} +exports.identity = identity; + +},{}],226:[function(require,module,exports){ +"use strict"; +exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); + +},{}],227:[function(require,module,exports){ +"use strict"; +exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; }); + +},{}],228:[function(require,module,exports){ +"use strict"; +function isDate(value) { + return value instanceof Date && !isNaN(+value); +} +exports.isDate = isDate; + +},{}],229:[function(require,module,exports){ +"use strict"; +function isFunction(x) { + return typeof x === 'function'; +} +exports.isFunction = isFunction; + +},{}],230:[function(require,module,exports){ +"use strict"; +var isArray_1 = require('../util/isArray'); +function isNumeric(val) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0; +} +exports.isNumeric = isNumeric; +; + +},{"../util/isArray":226}],231:[function(require,module,exports){ +"use strict"; +function isObject(x) { + return x != null && typeof x === 'object'; +} +exports.isObject = isObject; + +},{}],232:[function(require,module,exports){ +"use strict"; +function isPromise(value) { + return value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; +} +exports.isPromise = isPromise; + +},{}],233:[function(require,module,exports){ +"use strict"; +function isScheduler(value) { + return value && typeof value.schedule === 'function'; +} +exports.isScheduler = isScheduler; + +},{}],234:[function(require,module,exports){ +"use strict"; +/* tslint:disable:no-empty */ +function noop() { } +exports.noop = noop; + +},{}],235:[function(require,module,exports){ +"use strict"; +var noop_1 = require('./noop'); +/* tslint:enable:max-line-length */ +function pipe() { + var fns = []; + for (var _i = 0; _i < arguments.length; _i++) { + fns[_i - 0] = arguments[_i]; + } + return pipeFromArray(fns); +} +exports.pipe = pipe; +/* @internal */ +function pipeFromArray(fns) { + if (!fns) { + return noop_1.noop; + } + if (fns.length === 1) { + return fns[0]; + } + return function piped(input) { + return fns.reduce(function (prev, fn) { return fn(prev); }, input); + }; +} +exports.pipeFromArray = pipeFromArray; + +},{"./noop":234}],236:[function(require,module,exports){ +(function (global){ +"use strict"; +// CommonJS / Node have global context exposed as "global" variable. +// We don't want to include the whole node.d.ts this this compilation unit so we'll just fake +// the global "global" var for now. +var __window = typeof window !== 'undefined' && window; +var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && + self instanceof WorkerGlobalScope && self; +var __global = typeof global !== 'undefined' && global; +var _root = __window || __global || __self; +exports.root = _root; +// Workaround Closure Compiler restriction: The body of a goog.module cannot use throw. +// This is needed when used with angular/tsickle which inserts a goog.module statement. +// Wrap in IIFE +(function () { + if (!_root) { + throw new Error('RxJS could not find any global context (window, self, global)'); + } +})(); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],237:[function(require,module,exports){ +"use strict"; +var root_1 = require('./root'); +var isArrayLike_1 = require('./isArrayLike'); +var isPromise_1 = require('./isPromise'); +var isObject_1 = require('./isObject'); +var Observable_1 = require('../Observable'); +var iterator_1 = require('../symbol/iterator'); +var InnerSubscriber_1 = require('../InnerSubscriber'); +var observable_1 = require('../symbol/observable'); +function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) { + var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex); + if (destination.closed) { + return null; + } + if (result instanceof Observable_1.Observable) { + if (result._isScalar) { + destination.next(result.value); + destination.complete(); + return null; + } + else { + destination.syncErrorThrowable = true; + return result.subscribe(destination); + } + } + else if (isArrayLike_1.isArrayLike(result)) { + for (var i = 0, len = result.length; i < len && !destination.closed; i++) { + destination.next(result[i]); + } + if (!destination.closed) { + destination.complete(); + } + } + else if (isPromise_1.isPromise(result)) { + result.then(function (value) { + if (!destination.closed) { + destination.next(value); + destination.complete(); + } + }, function (err) { return destination.error(err); }) + .then(null, function (err) { + // Escaping the Promise trap: globally throw unhandled errors + root_1.root.setTimeout(function () { throw err; }); + }); + return destination; + } + else if (result && typeof result[iterator_1.iterator] === 'function') { + var iterator = result[iterator_1.iterator](); + do { + var item = iterator.next(); + if (item.done) { + destination.complete(); + break; + } + destination.next(item.value); + if (destination.closed) { + break; + } + } while (true); + } + else if (result && typeof result[observable_1.observable] === 'function') { + var obs = result[observable_1.observable](); + if (typeof obs.subscribe !== 'function') { + destination.error(new TypeError('Provided object does not correctly implement Symbol.observable')); + } + else { + return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex)); + } + } + else { + var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'"; + var msg = ("You provided " + value + " where a stream was expected.") + + ' You can provide an Observable, Promise, Array, or Iterable.'; + destination.error(new TypeError(msg)); + } + return null; +} +exports.subscribeToResult = subscribeToResult; + +},{"../InnerSubscriber":27,"../Observable":29,"../symbol/iterator":214,"../symbol/observable":215,"./isArrayLike":227,"./isObject":231,"./isPromise":232,"./root":236}],238:[function(require,module,exports){ +"use strict"; +var Subscriber_1 = require('../Subscriber'); +var rxSubscriber_1 = require('../symbol/rxSubscriber'); +var Observer_1 = require('../Observer'); +function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver) { + if (nextOrObserver instanceof Subscriber_1.Subscriber) { + return nextOrObserver; + } + if (nextOrObserver[rxSubscriber_1.rxSubscriber]) { + return nextOrObserver[rxSubscriber_1.rxSubscriber](); + } + } + if (!nextOrObserver && !error && !complete) { + return new Subscriber_1.Subscriber(Observer_1.empty); + } + return new Subscriber_1.Subscriber(nextOrObserver, error, complete); +} +exports.toSubscriber = toSubscriber; + +},{"../Observer":30,"../Subscriber":36,"../symbol/rxSubscriber":216}],239:[function(require,module,exports){ +"use strict"; +var errorObject_1 = require('./errorObject'); +var tryCatchTarget; +function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } + catch (e) { + errorObject_1.errorObject.e = e; + return errorObject_1.errorObject; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} +exports.tryCatch = tryCatch; +; + +},{"./errorObject":224}],240:[function(require,module,exports){ +// threejs.org/license +(function(m,ja){"object"===typeof exports&&"undefined"!==typeof module?ja(exports):"function"===typeof define&&define.amd?define(["exports"],ja):ja(m.THREE=m.THREE||{})})(this,function(m){function ja(){}function C(a,b){this.x=a||0;this.y=b||0}function K(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];0=d||0 0 ) {\n\t\tfloat fogFactor = 0.0;\n\t\tif ( fogType == 1 ) {\n\t\t\tfogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t\t} else {\n\t\t\tconst float LOG2 = 1.442695;\n\t\t\tfogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );\n\t\t\tfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n\t\t}\n\t\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\t}\n}"].join("\n")); +b.compileShader(y);b.compileShader(Y);b.attachShader(M,y);b.attachShader(M,Y);b.linkProgram(M);ha=M;B=b.getAttribLocation(ha,"position");J=b.getAttribLocation(ha,"uv");f=b.getUniformLocation(ha,"uvOffset");g=b.getUniformLocation(ha,"uvScale");h=b.getUniformLocation(ha,"rotation");k=b.getUniformLocation(ha,"scale");l=b.getUniformLocation(ha,"color");q=b.getUniformLocation(ha,"map");n=b.getUniformLocation(ha,"opacity");t=b.getUniformLocation(ha,"modelViewMatrix");r=b.getUniformLocation(ha,"projectionMatrix"); +m=b.getUniformLocation(ha,"fogType");v=b.getUniformLocation(ha,"fogDensity");w=b.getUniformLocation(ha,"fogNear");x=b.getUniformLocation(ha,"fogFar");z=b.getUniformLocation(ha,"fogColor");b.getUniformLocation(ha,"fogDepth");I=b.getUniformLocation(ha,"alphaTest");M=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");M.width=8;M.height=8;y=M.getContext("2d");y.fillStyle="white";y.fillRect(0,0,8,8);He=new tc(M)}c.useProgram(ha);c.initAttributes();c.enableAttribute(B);c.enableAttribute(J); +c.disableUnusedAttributes();c.disable(b.CULL_FACE);c.enable(b.BLEND);b.bindBuffer(b.ARRAY_BUFFER,za);b.vertexAttribPointer(B,2,b.FLOAT,!1,16,0);b.vertexAttribPointer(J,2,b.FLOAT,!1,16,8);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,la);b.uniformMatrix4fv(r,!1,V.projectionMatrix.elements);c.activeTexture(b.TEXTURE0);b.uniform1i(q,0);y=M=0;(Y=p.fog)?(b.uniform3f(z,Y.color.r,Y.color.g,Y.color.b),Y.isFog?(b.uniform1f(w,Y.near),b.uniform1f(x,Y.far),b.uniform1i(m,1),y=M=1):Y.isFogExp2&&(b.uniform1f(v,Y.density), +b.uniform1i(m,2),y=M=2)):(b.uniform1i(m,0),y=M=0);for(var A=0,ua=u.length;Ab&&(b=a[c]);return b}function D(){Object.defineProperty(this,"id",{value:Pf+=2});this.uuid=R.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes= +{};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Lb(a,b,c,d,e,f){N.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new jb(a,b,c,d,e,f));this.mergeVertices()}function jb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,m,ta,za,la){var z=f/ta,u=g/za,v=f/2,w=g/2,I=m/2;g=ta+1;var B=za+1,x=f=0,J,y,C=new p;for(y=0;yl;l++){if(n=d[l])if(h=n[0],n=n[1]){q&&e.addAttribute("morphTarget"+l,q[h]);f&&e.addAttribute("morphNormal"+l,f[h]);c[l]=n;continue}c[l]=0}g.getUniforms().setValue(a,"morphTargetInfluences",c)}}}function Xf(a,b,c){var d,e,f;this.setMode=function(a){d= +a};this.setIndex=function(a){e=a.type;f=a.bytesPerElement};this.render=function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES?c.faces+=h/3:d===a.POINTS&&(c.points+=h)};this.renderInstances=function(g,h,k){var l=b.get("ANGLE_instanced_arrays");null===l?console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(l.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+= +k*g.maxInstancedCount,d===a.TRIANGLES?c.faces+=g.maxInstancedCount*k/3:d===a.POINTS&&(c.points+=g.maxInstancedCount*k))}}function Yf(a,b,c){var d;this.setMode=function(a){d=a};this.render=function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES?c.faces+=f/3:d===a.POINTS&&(c.points+=f)};this.renderInstances=function(e,f,g){var h=b.get("ANGLE_instanced_arrays");if(null===h)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."); +else{var k=e.attributes.position;k.isInterleavedBufferAttribute?(g=k.data.count,h.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount)):h.drawArraysInstancedANGLE(d,f,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES?c.faces+=e.maxInstancedCount*g/3:d===a.POINTS&&(c.points+=e.maxInstancedCount*g)}}}function Zf(a,b,c){function d(a){a=a.target;var g=e[a.id];null!==g.index&&b.remove(g.index);for(var k in g.attributes)b.remove(g.attributes[k]);a.removeEventListener("dispose", +d);delete e[a.id];if(k=f[a.id])b.remove(k),delete f[a.id];if(k=f[g.id])b.remove(k),delete f[g.id];c.geometries--}var e={},f={};return{get:function(a,b){var f=e[b.id];if(f)return f;b.addEventListener("dispose",d);b.isBufferGeometry?f=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new D).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.geometries++;return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f], +a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=c[f],e=0,g=d.length;e/gm,function(a,c){a=W[c];if(void 0===a)throw Error("Can not resolve #include <"+c+">");return Sd(a)})}function Ne(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g, +function(a,c,d,e){a="";for(c=parseInt(c);cb||a.height>b){b/=Math.max(a.width,a.height);var c=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");c.width=Math.floor(a.width*b);c.height=Math.floor(a.height*b);c.getContext("2d").drawImage(a, +0,0,a.width,a.height,0,0,c.width,c.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+c.width+"x"+c.height,a);return c}return a}function k(a){return R.isPowerOfTwo(a.width)&&R.isPowerOfTwo(a.height)}function l(a,b){return a.generateMipmaps&&b&&1003!==a.minFilter&&1006!==a.minFilter}function q(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function n(b){b=b.target;b.removeEventListener("dispose",n);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube); +else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function t(b){b=b.target;b.removeEventListener("dispose",t);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer), +c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function r(b,q){var t=d.get(b);if(0p;p++)u[p]=q||r?r?b.image[p].image:b.image[p]:h(b.image[p],e.maxCubemapSize); +var v=k(u[0]),w=f.convert(b.format),z=f.convert(b.type);m(a.TEXTURE_CUBE_MAP,b,v);for(p=0;6>p;p++)if(q)for(var x,I=u[p].mipmaps,y=0,C=I.length;yq;q++)e.__webglFramebuffer[q]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);m(a.TEXTURE_CUBE_MAP,b.texture,n);for(q=0;6>q;q++)p(e.__webglFramebuffer[q],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+q); +l(b.texture,n)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),m(a.TEXTURE_2D,b.texture,n),p(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),l(b.texture,n)&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported"); +a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);r(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER, +a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),w(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),w(e.__webglDepthbuffer, +b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);l(e,f)&&(b=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function lg(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},remove:function(b){delete a[b.uuid]},clear:function(){a={}}}}function mg(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture(); +a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b=Z.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+Z.maxTextures);G+=1;return a}; +this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);T.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);T.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&& +b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?T.setTextureCube(b,c):T.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return H};this.setRenderTarget=function(a){(H=a)&&void 0===U.get(a).__webglFramebuffer&&T.setupRenderTarget(a);var b=null,c=!1;a?(b=U.get(a).__webglFramebuffer,a.isWebGLRenderTargetCube&& +(b=b[a.activeCubeFace],c=!0),Q.copy(a.viewport),S.copy(a.scissor),W=a.scissorTest):(Q.copy(ca).multiplyScalar(O),S.copy(ea).multiplyScalar(O),W=Oe);M!==b&&(F.bindFramebuffer(F.FRAMEBUFFER,b),M=b);ba.viewport(Q);ba.scissor(S);ba.setScissorTest(W);c&&(c=U.get(a.texture),F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,c.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=U.get(a).__webglFramebuffer; +if(g){var h=!1;g!==M&&(F.bindFramebuffer(F.FRAMEBUFFER,g),h=!0);try{var l=a.texture,k=l.format,n=l.type;1023!==k&&oa.convert(k)!==F.getParameter(F.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||oa.convert(n)===F.getParameter(F.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ia.get("OES_texture_float")||ia.get("WEBGL_color_buffer_float"))||1016===n&&ia.get("EXT_color_buffer_half_float")? +F.checkFramebufferStatus(F.FRAMEBUFFER)===F.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&F.readPixels(b,c,d,e,oa.convert(k),oa.convert(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&F.bindFramebuffer(F.FRAMEBUFFER,M)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")}} +function Ob(a,b){this.name="";this.color=new H(a);this.density=void 0!==b?b:2.5E-4}function Pb(a,b,c){this.name="";this.color=new H(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function od(){A.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Xd(a,b,c,d,e){A.call(this);this.lensFlares=[];this.positionScreen=new p;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function Za(a){Q.call(this);this.type="SpriteMaterial"; +this.color=new H(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function Cc(a){A.call(this);this.type="Sprite";this.material=void 0!==a?a:new Za}function Dc(){A.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Ec(a,b){a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton boneInverses is the wrong length."), +this.boneInverses=[],a=0,b=this.bones.length;a=a.HAVE_CURRENT_DATA&&(q.needsUpdate=!0);requestAnimationFrame(l)}ea.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var q=this;requestAnimationFrame(l)} +function Rb(a,b,c,d,e,f,g,h,k,l,q,n){ea.call(this,null,f,g,h,k,l,d,e,q,n);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function Gc(a,b,c,d,e,f,g,h,k,l){l=void 0!==l?l:1026;if(1026!==l&&1027!==l)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===l&&(c=1012);void 0===c&&1027===l&&(c=1020);ea.call(this,null,d,e,f,g,h,l,c,k);this.image={width:a,height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!== +h?h:1003;this.generateMipmaps=this.flipY=!1}function Sb(a){D.call(this);this.type="WireframeGeometry";var b=[],c,d,e,f=[0,0],g={},h=["a","b","c"];if(a&&a.isGeometry){var k=a.faces;var l=0;for(d=k.length;lc;c++){var n=q[h[c]];var t=q[h[(c+1)%3]];f[0]=Math.min(n,t);f[1]=Math.max(n,t);n=f[0]+","+f[1];void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]})}}for(n in g)l=g[n],h=a.vertices[l.index1],b.push(h.x,h.y,h.z),h=a.vertices[l.index2],b.push(h.x,h.y,h.z)}else if(a&&a.isBufferGeometry){var h= +new p;if(null!==a.index){k=a.attributes.position;q=a.index;var r=a.groups;0===r.length&&(r=[{start:0,count:q.count,materialIndex:0}]);a=0;for(e=r.length;ac;c++)n=q.getX(l+c),t=q.getX(l+(c+1)%3),f[0]=Math.min(n,t),f[1]=Math.max(n,t),n=f[0]+","+f[1],void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]});for(n in g)l=g[n],h.fromBufferAttribute(k,l.index1),b.push(h.x,h.y,h.z),h.fromBufferAttribute(k,l.index2),b.push(h.x,h.y,h.z)}else for(k=a.attributes.position, +l=0,d=k.count/3;lc;c++)g=3*l+c,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z),g=3*l+(c+1)%3,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z)}this.addAttribute("position",new y(b,3))}function Hc(a,b,c){N.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Tb(a,b,c));this.mergeVertices()}function Tb(a,b,c){D.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h= +new p,k=new p,l=new p,q=new p,n=new p,t,r,m=b+1;for(t=0;t<=c;t++){var v=t/c;for(r=0;r<=b;r++){var w=r/b,k=a(w,v,k);e.push(k.x,k.y,k.z);0<=w-1E-5?(l=a(w-1E-5,v,l),q.subVectors(k,l)):(l=a(w+1E-5,v,l),q.subVectors(l,k));0<=v-1E-5?(l=a(w,v-1E-5,l),n.subVectors(k,l)):(l=a(w,v+1E-5,l),n.subVectors(l,k));h.crossVectors(q,n).normalize();f.push(h.x,h.y,h.z);g.push(w,v)}}for(t=0;td&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===c.z&&(k[b]=d/2/Math.PI+.5)}D.call(this);this.type="PolyhedronBufferGeometry"; +this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],k=[];(function(a){for(var c=new p,d=new p,g=new p,h=0;he&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",new y(h,3));this.addAttribute("normal",new y(h.slice(),3));this.addAttribute("uv",new y(k,2));0===d?this.computeVertexNormals(): +this.normalizeNormals()}function Jc(a,b){N.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ub(a,b));this.mergeVertices()}function Ub(a,b){qa.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Kc(a,b){N.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new nb(a,b));this.mergeVertices()} +function nb(a,b){qa.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Lc(a,b){N.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Vb(a,b));this.mergeVertices()}function Vb(a,b){var c=(1+Math.sqrt(5))/2;qa.call(this,[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11, +5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Mc(a,b){N.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Wb(a,b));this.mergeVertices()}function Wb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;qa.call(this,[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0, +d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Nc(a,b,c,d,e,f){N.call(this);this.type="TubeGeometry";this.parameters={path:a, +tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Xb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Xb(a,b,c,d,e){function f(e){q=a.getPointAt(e/b,q);var f=g.normals[e];e=g.binormals[e];for(t=0;t<=d;t++){var l=t/d*Math.PI*2,n=Math.sin(l),l=-Math.cos(l);k.x=l*f.x+n*e.x;k.y=l*f.y+n*e.y;k.z=l*f.z+n*e.z;k.normalize();u.push(k.x, +k.y,k.z);h.x=q.x+c*k.x;h.y=q.y+c*k.y;h.z=q.z+c*k.z;m.push(h.x,h.y,h.z)}}D.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new p,k=new p,l=new C,q=new p,n,t,m=[],u=[],v=[],w=[];for(n=0;nq;q++){var n=l[f[q]];var t=l[f[(q+1)%3]];d[0]=Math.min(n,t);d[1]=Math.max(n,t);n=d[0]+","+d[1];void 0===e[n]?e[n]={index1:d[0],index2:d[1],face1:h,face2:void 0}:e[n].face2=h}for(n in e)if(d=e[n],void 0===d.face2||g[d.face1].normal.dot(g[d.face2].normal)<=b)f=a[d.index1],c.push(f.x,f.y,f.z),f=a[d.index2],c.push(f.x,f.y,f.z);this.addAttribute("position", +new y(c,3))}function pb(a,b,c,d,e,f,g,h){N.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Sa(a,b,c,d,e,f,g,h));this.mergeVertices()}function Sa(a,b,c,d,e,f,g,h){function k(c){var e,f=new C,k=new p,r=0,v=!0===c?a:b,z=!0===c?1:-1;var y=u;for(e=1;e<=d;e++)n.push(0,w*z,0),t.push(0,z,0),m.push(.5,.5),u++;var A=u;for(e=0;e<=d;e++){var D=e/d*h+g,L=Math.cos(D), +D=Math.sin(D);k.x=v*D;k.y=w*z;k.z=v*L;n.push(k.x,k.y,k.z);t.push(0,z,0);f.x=.5*L+.5;f.y=.5*D*z+.5;m.push(f.x,f.y);u++}for(e=0;ethis.duration&&this.resetDuration();this.optimize()}function Id(a){this.manager=void 0!==a?a:wa;this.textures={}}function ae(a){this.manager=void 0!==a?a:wa}function kc(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function be(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."), +a=void 0);this.manager=void 0!==a?a:wa;this.withCredentials=!1}function Re(a){this.manager=void 0!==a?a:wa;this.texturePath=""}function Se(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*c-2*d+b+e)*a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function yb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function zb(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}function S(){this.type="Curve";this.arcLengthDivisions=200}function Ka(a,b){S.call(this);this.type="LineCurve";this.v1=a|| +new C;this.v2=b||new C}function Ab(){S.call(this);this.type="CurvePath";this.curves=[];this.autoClose=!1}function Na(a,b,c,d,e,f,g,h){S.call(this);this.type="EllipseCurve";this.aX=a||0;this.aY=b||0;this.xRadius=c||1;this.yRadius=d||1;this.aStartAngle=e||0;this.aEndAngle=f||2*Math.PI;this.aClockwise=g||!1;this.aRotation=h||0}function ab(a){S.call(this);this.type="SplineCurve";this.points=a||[]}function bb(a,b,c,d){S.call(this);this.type="CubicBezierCurve";this.v0=a||new C;this.v1=b||new C;this.v2= +c||new C;this.v3=d||new C}function cb(a,b,c){S.call(this);this.type="QuadraticBezierCurve";this.v0=a||new C;this.v1=b||new C;this.v2=c||new C}function Bb(a){Ab.call(this);this.type="Path";this.currentPoint=new C;a&&this.setFromPoints(a)}function Cb(a){Bb.call(this,a);this.type="Shape";this.holes=[]}function ce(){this.type="ShapePath";this.subPaths=[];this.currentPath=null}function de(a){this.type="Font";this.data=a}function Te(a){this.manager=void 0!==a?a:wa}function ee(a){this.manager=void 0!==a? +a:wa}function Ue(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new U;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new U;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function $c(a,b,c){A.call(this);this.type="CubeCamera";var d=new U(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new p(1,0,0));this.add(d);var e=new U(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new p(-1,0,0));this.add(e);var f=new U(90,1,a,b);f.up.set(0,0,1);f.lookAt(new p(0,1,0)); +this.add(f);var g=new U(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new p(0,-1,0));this.add(g);var h=new U(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new p(0,0,1));this.add(h);var k=new U(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new p(0,0,-1));this.add(k);this.renderTarget=new Ib(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.update=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,l=c.texture.generateMipmaps;c.texture.generateMipmaps= +!1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=l;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)};this.clear=function(a,b,c,d){for(var e=this.renderTarget,f=0;6>f;f++)e.activeCubeFace=f,a.setRenderTarget(e),a.clear(b,c,d);a.setRenderTarget(null)}}function fe(){A.call(this);this.type="AudioListener";this.context=ge.getContext();this.gain= +this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function lc(a){A.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.offset=this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function he(a){lc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)} +function ie(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function je(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function Ve(a, +b,c){c=c||na.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function na(a,b,c){this.path=b;this.parsedPath=c||na.parseTrackName(b);this.node=na.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function We(){this.uuid=R.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var a={};this._indicesByUUID=a;for(var b=0,c=arguments.length;b!==c;++b)a[arguments[b].uuid]=b;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath= +{};var d=this;this.stats={objects:{get total(){return d._objects.length},get inUse(){return this.total-d.nCachedObjects_}},get bindingsPerObject(){return d._bindings.length}}}function Xe(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant= +this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function Ye(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Jd(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."), +a=b);this.value=a}function ke(){D.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function le(a,b,c,d){this.uuid=R.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function mc(a,b){this.uuid=R.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function me(a,b,c){mc.call(this,a,b);this.meshPerAttribute=c||1}function ne(a, +b,c){P.call(this,a,b);this.meshPerAttribute=c||1}function Ze(a,b,c,d){this.ray=new lb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function $e(a,b){return a.distance-b.distance}function oe(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e= +a.length;dc;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new y(b,3));b=new O({fog:!1});this.cone=new ca(a,b);this.add(this.cone);this.update()}function df(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;ca?-1:0e;e++)8===e||13===e||18===e||23===e?d+="-":14===e?d+="4":(2>=b&&(b=33554432+16777216*Math.random()|0),c=b&15,b>>=4,d+=a[19===e?c&3|8:c]);return d}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a, +b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*R.DEG2RAD},radToDeg:function(a){return a*R.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},ceilPowerOfTwo:function(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))},floorPowerOfTwo:function(a){return Math.pow(2, +Math.floor(Math.log(a)/Math.LN2))}};Object.defineProperties(C.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(C.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break; +default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this}, +addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y; +return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},applyMatrix3:function(a){var b=this.x,c=this.y;a=a.elements;this.x=a[0]*b+a[3]*c+a[6];this.y=a[1]*b+a[4]*c+a[7];return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y= +Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x); +this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},manhattanLength:function(){return Math.abs(this.x)+ +Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+= +(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b); +return this},rotateAround:function(a,b){var c=Math.cos(b);b=Math.sin(b);var d=this.x-a.x,e=this.y-a.y;this.x=d*c-e*b+a.x;this.y=d*b+e*c+a.y;return this}});Object.assign(K.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,l,q,n,t,m,p,v){var r=this.elements;r[0]=a;r[4]=b;r[8]=c;r[12]=d;r[1]=e;r[5]=f;r[9]=g;r[13]=h;r[2]=k;r[6]=l;r[10]=q;r[14]=n;r[3]=t;r[7]=m;r[11]=p;r[15]=v;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new K).fromArray(this.elements)}, +copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x, +b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new p;return function(b){var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order."); +var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){var k=f*h;var l=f*e;var q=c*h;a=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=l+q*d;b[5]=k-a*d;b[9]=-c*g;b[2]=a-k*d;b[6]=q+l*d;b[10]=f*g}else"YXZ"===a.order?(k=g*h,l=g*e,q=d*h,a=d*e,b[0]=k+a*c,b[4]=q*c-l,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=l*c-q,b[6]=a+k*c,b[10]=f*g):"ZXY"===a.order?(k=g*h,l=g*e,q=d*h,a=d*e,b[0]=k-a*c,b[4]=-f*e,b[8]=q+l*c,b[1]=l+q*c,b[5]=f*h,b[9]= +a-k*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(k=f*h,l=f*e,q=c*h,a=c*e,b[0]=g*h,b[4]=q*d-l,b[8]=k*d+a,b[1]=g*e,b[5]=a*d+k,b[9]=l*d-q,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(k=f*g,l=f*d,q=c*g,a=c*d,b[0]=g*h,b[4]=a-k*e,b[8]=q*e+l,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=l*e+q,b[10]=k-a*e):"XZY"===a.order&&(k=f*g,l=f*d,q=c*g,a=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=k*e+a,b[5]=f*h,b[9]=l*e-q,b[2]=q*e-l,b[6]=c*h,b[10]=a*e+k);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b= +this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,k=e+e;a=c*g;var l=c*h,c=c*k,q=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(q+e);b[4]=l-f;b[8]=c+h;b[1]=l+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+q);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},lookAt:function(){var a=new p,b=new p,c=new p;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4, +c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements; +b=this.elements;a=c[0];var e=c[4],f=c[8],g=c[12],h=c[1],k=c[5],l=c[9],q=c[13],n=c[2],m=c[6],r=c[10],p=c[14],v=c[3],w=c[7],x=c[11],c=c[15],z=d[0],I=d[4],B=d[8],J=d[12],y=d[1],C=d[5],A=d[9],D=d[13],E=d[2],H=d[6],L=d[10],Y=d[14],N=d[3],M=d[7],V=d[11],d=d[15];b[0]=a*z+e*y+f*E+g*N;b[4]=a*I+e*C+f*H+g*M;b[8]=a*B+e*A+f*L+g*V;b[12]=a*J+e*D+f*Y+g*d;b[1]=h*z+k*y+l*E+q*N;b[5]=h*I+k*C+l*H+q*M;b[9]=h*B+k*A+l*L+q*V;b[13]=h*J+k*D+l*Y+q*d;b[2]=n*z+m*y+r*E+p*N;b[6]=n*I+m*C+r*H+p*M;b[10]=n*B+m*A+r*L+p*V;b[14]=n*J+m* +D+r*Y+p*d;b[3]=v*z+w*y+x*E+c*N;b[7]=v*I+w*C+x*H+c*M;b[11]=v*B+w*A+x*L+c*V;b[15]=v*J+w*D+x*Y+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;cthis.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.copy(this);c=1/g;var f=1/h,l=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=l;b.elements[9]*=l;b.elements[10]*=l;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs."); +var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),l=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*l;g[14]=-((f+e)*l);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements; +a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}});Object.assign(Z,{slerp:function(a,b,c,d){return c.copy(a).slerp(b, +d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],l=c[d+2];c=c[d+3];d=e[f+0];var q=e[f+1],n=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||l!==n){f=1-g;var m=h*d+k*q+l*n+c*e,r=0<=m?1:-1,p=1-m*m;p>Number.EPSILON&&(p=Math.sqrt(p),m=Math.atan2(p,m*r),f=Math.sin(f*m)/p,g=Math.sin(g*m)/p);r*=g;h=h*f+d*r;k=k*f+q*r;l=l*f+n*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+l*l+c*c),h*=g,k*=g,l*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=l;a[b+3]=c}});Object.defineProperties(Z.prototype,{x:{get:function(){return this._x}, +set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(Z.prototype,{set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z, +this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z;a=a.order;var f=Math.cos,g=Math.sin,h=f(c/2),k=f(d/2),f=f(e/2),c=g(c/2),d=g(d/2),e=g(e/2);"XYZ"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"YXZ"===a?(this._x=c*k*f+ +h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"ZXY"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"ZYX"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"YZX"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f-c*d*e):"XZY"===a&&(this._x=c*k*f-h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a, +b){b/=2;var c=Math.sin(b);this._x=a.x*c;this._y=a.y*c;this._z=a.z*c;this._w=Math.cos(b);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],l=c+f+b;0f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y= +.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new p,b;return function(c,d){void 0===a&&(a=new p);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*= +-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this}, +multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z;a=a._w;var f=b._x,g=b._y,h=b._z;b=b._w;this._x=c*b+a*f+d*h-e*g;this._y=d*b+a*g+e*f-c*h;this._z=e*b+a*h+c*g-d*f;this._w=a*b-c*f-d*g-e*h;this.onChangeCallback(); +return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;a=Math.sqrt(1-g*g);if(.001>Math.abs(a))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var h=Math.atan2(a,g),g=Math.sin((1-b)*h)/a;b=Math.sin(b*h)/a; +this._w=f*g+this._w*b;this._x=c*g+this._x*b;this._y=d*g+this._y*b;this._z=e*g+this._z*b;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback= +a;return this},onChangeCallback:function(){}});Object.assign(p.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x; +case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this}, +addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z= +a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new Z;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."); +return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new Z;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]* +d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,l=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-l*-f;this.y=k*a+b*-f+l*-e-h*-g;this.z=l*a+b*-g+h*-f-k*-e;return this},project:function(){var a=new K;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new K;return function(b){a.multiplyMatrices(b.matrixWorld, +a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x= +Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a=new p,b=new p;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x= +Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x= +-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x- +this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b)):this.crossVectors(this,a)},crossVectors:function(a,b){var c=a.x,d=a.y;a=a.z;var e=b.x,f=b.y;b=b.z;this.x=d*b-a*f;this.y=a*e-c*b;this.z=c*f-d*e;return this},projectOnVector:function(a){var b= +a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new p;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new p;return function(b){return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(R.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x- +a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y= +a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a= +[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(ra.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var l=this.elements;l[0]=a;l[1]=d;l[2]=g;l[3]=b;l[4]=e;l[5]=h;l[6]=c;l[7]=f;l[8]=k;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)}, +copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;cc;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c= +this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}});var kf=0;ea.DEFAULT_IMAGE=void 0;ea.DEFAULT_MAPPING=300;Object.defineProperty(ea.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ea.prototype,ja.prototype,{constructor:ea,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping= +a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.center.copy(a.center);this.rotation=a.rotation;this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrix.copy(a.matrix);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding; +return this},toJSON:function(a){var b=void 0===a||"string"===typeof a;if(!b&&void 0!==a.textures[this.uuid])return a.textures[this.uuid];var c={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY}; +if(void 0!==this.image){var d=this.image;void 0===d.uuid&&(d.uuid=R.generateUUID());if(!b&&void 0===a.images[d.uuid]){var e=a.images,f=d.uuid,g=d.uuid;if(d instanceof HTMLCanvasElement)var h=d;else{h=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");h.width=d.width;h.height=d.height;var k=h.getContext("2d");d instanceof ImageData?k.putImageData(d,0,0):k.drawImage(d,0,0,d.width,d.height)}h=2048a.x||1a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)% +2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(da.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break; +case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."), +this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a, +b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]* +e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){a=a.elements;var b=a[0];var c=a[4];var d=a[8],e=a[1],f=a[5],g=a[9];var h=a[2];var k=a[6];var l=a[10];if(.01>Math.abs(c-e)&&.01>Math.abs(d-h)&&.01>Math.abs(g-k)){if(.1>Math.abs(c+ +e)&&.1>Math.abs(d+h)&&.1>Math.abs(g+k)&&.1>Math.abs(b+f+l-3))return this.set(1,0,0,0),this;a=Math.PI;b=(b+1)/2;f=(f+1)/2;l=(l+1)/2;c=(c+e)/4;d=(d+h)/4;g=(g+k)/4;b>f&&b>l?.01>b?(k=0,c=h=.707106781):(k=Math.sqrt(b),h=c/k,c=d/k):f>l?.01>f?(k=.707106781,h=0,c=.707106781):(h=Math.sqrt(f),k=c/h,c=g/h):.01>l?(h=k=.707106781,c=0):(c=Math.sqrt(l),k=d/c,h=g/c);this.set(k,h,c,a);return this}a=Math.sqrt((k-g)*(k-g)+(d-h)*(d-h)+(e-c)*(e-c));.001>Math.abs(a)&&(a=1);this.x=(k-g)/a;this.y=(d-h)/a;this.z=(e-c)/a; +this.w=Math.acos((b+f+l-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w, +this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new da,b=new da);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z); +this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this}, +dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+= +(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a, +b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});Object.assign(Hb.prototype,ja.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height= +a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ib.prototype=Object.create(Hb.prototype);Ib.prototype.constructor=Ib;Ib.prototype.isWebGLRenderTargetCube=!0;fb.prototype=Object.create(ea.prototype);fb.prototype.constructor=fb;fb.prototype.isDataTexture=!0;Ua.prototype=Object.create(ea.prototype);Ua.prototype.constructor= +Ua;Ua.prototype.isCubeTexture=!0;Object.defineProperty(Ua.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Be=new ea,Ce=new Ua,we=[],ye=[],Ae=new Float32Array(16),ze=new Float32Array(9);Ge.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Od=/([\w\d_]+)(\])?(\[|\.)?/g;gb.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};gb.prototype.setOptional=function(a, +b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};gb.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};gb.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var sg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231, +cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539, +deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536, +lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154, +mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519, +royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Object.assign(H.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){a&& +a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=R.euclideanModulo(b, +1);c=R.clamp(c,0,1);d=R.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255, +parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d=parseFloat(c[1])/360, +e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0=h?k/(e+f): +k/(2-e-f);switch(e){case b:g=(c-d)/k+(c 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n", +bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n", +clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n", +clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n", +color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\n", +cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n", +defaultnormal_vertex:"vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n", +emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n",encodings_fragment:" gl_FragColor = linearToOutputTexel( gl_FragColor );\n",encodings_pars_fragment:"\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n", +envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n", +envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n", +envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n",envmap_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n", +fog_vertex:"\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n varying float fogDepth;\n#endif\n",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n", +gradientmap_pars_fragment:"#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n", +lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n", +lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n", +lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n", +lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n", +lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n", +lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n", +logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n", +map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n", +metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n", +morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n", +normal_fragment:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n", +normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n", +packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n", +premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",project_vertex:"vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n",dithering_fragment:"#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n",dithering_pars_fragment:"#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n", +roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n", +shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n", +shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n", +shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n", +skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n", +skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n", +specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n", +uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\n", +uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif", +uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n", +cube_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n", +depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n", +distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}\n", +equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n", +linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}\n", +meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshphysical_vert:"#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}\n", +normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n", +normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n", +points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n}\n",shadow_vert:"#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"}, +mb={basic:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.fog]),vertexShader:W.meshbasic_vert,fragmentShader:W.meshbasic_frag},lambert:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.fog,E.lights,{emissive:{value:new H(0)}}]),vertexShader:W.meshlambert_vert,fragmentShader:W.meshlambert_frag},phong:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.bumpmap,E.normalmap,E.displacementmap,E.gradientmap, +E.fog,E.lights,{emissive:{value:new H(0)},specular:{value:new H(1118481)},shininess:{value:30}}]),vertexShader:W.meshphong_vert,fragmentShader:W.meshphong_frag},standard:{uniforms:Ea.merge([E.common,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.bumpmap,E.normalmap,E.displacementmap,E.roughnessmap,E.metalnessmap,E.fog,E.lights,{emissive:{value:new H(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag},points:{uniforms:Ea.merge([E.points, +E.fog]),vertexShader:W.points_vert,fragmentShader:W.points_frag},dashed:{uniforms:Ea.merge([E.common,E.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:W.linedashed_vert,fragmentShader:W.linedashed_frag},depth:{uniforms:Ea.merge([E.common,E.displacementmap]),vertexShader:W.depth_vert,fragmentShader:W.depth_frag},normal:{uniforms:Ea.merge([E.common,E.bumpmap,E.normalmap,E.displacementmap,{opacity:{value:1}}]),vertexShader:W.normal_vert,fragmentShader:W.normal_frag},cube:{uniforms:{tCube:{value:null}, +tFlip:{value:-1},opacity:{value:1}},vertexShader:W.cube_vert,fragmentShader:W.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:W.equirect_vert,fragmentShader:W.equirect_frag},distanceRGBA:{uniforms:Ea.merge([E.common,E.displacementmap,{referencePosition:{value:new p},nearDistance:{value:1},farDistance:{value:1E3}}]),vertexShader:W.distanceRGBA_vert,fragmentShader:W.distanceRGBA_frag},shadow:{uniforms:Ea.merge([E.lights,E.fog,{color:{value:new H(0)},opacity:{value:1}}]),vertexShader:W.shadow_vert, +fragmentShader:W.shadow_frag}};mb.physical={uniforms:Ea.merge([mb.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag};Object.assign(kd.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<= +this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min); +this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});tc.prototype=Object.create(ea.prototype);tc.prototype.constructor=tc;var Lf=0;Object.assign(Q.prototype,ja.prototype,{isMaterial:!0,onBeforeCompile:function(){},setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+ +b+"' parameter is undefined.");else if("shading"===b)console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===c?!0:!1;else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c= +void 0===a||"string"===typeof a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());1!==this.emissiveIntensity&&(d.emissiveIntensity=this.emissiveIntensity); +this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&& +this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid); +this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&& +(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);!0===this.flatShading&&(d.flatShading=this.flatShading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0!==this.rotation&&(d.rotation=this.rotation); +1!==this.linewidth&&(d.linewidth=this.linewidth);void 0!==this.dashSize&&(d.dashSize=this.dashSize);void 0!==this.gapSize&&(d.gapSize=this.gapSize);void 0!==this.scale&&(d.scale=this.scale);!0===this.dithering&&(d.dithering=!0);0e&&(e=l);q>f&&(f=q);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b= +Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;he&&(e=l);q>f&&(f=q);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y||a.zthis.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<= +this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new p).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y||a.max.zthis.max.z?!1:!0},intersectsSphere:function(){var a=new p;return function(b){this.clampPoint(b.center, +a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){if(0=a.constant},clampPoint:function(a, +b){return(b||new p).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new p;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new p;return function(b){b=b||new Da;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a= +[new p,new p,new p,new p,new p,new p,new p,new p];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b); +a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Da.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new Oa;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=c=0,f=b.length;e=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<= +b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(a.distanceToPoint(this.center))<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a);b=b||new p;b.copy(a);c>this.radius*this.radius&&(b.sub(this.center).normalize(),b.multiplyScalar(this.radius).add(this.center));return b},getBoundingBox:function(a){a=a||new Oa;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a); +this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Aa.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a= +new p,b=new p;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+ +this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return(b||new p).copy(this.normal).multiplyScalar(-this.distanceToPoint(a)).add(a)},intersectLine:function(){var a=new p;return function(b,c){c=c||new p;var d=b.delta(a),e=this.normal.dot(d);if(0===e){if(0===this.distanceToPoint(b.start))return c.copy(b.start)}else if(e=-(b.start.dot(this.normal)+this.constant)/e,!(0>e||1b&&0a&&0c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes, +c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],l=c[7],q=c[8],n=c[9],m=c[10],r=c[11],p=c[12],v=c[13],w=c[14],c=c[15];b[0].setComponents(f-a,l-g,r-q,c-p).normalize();b[1].setComponents(f+a,l+g,r+q,c+p).normalize();b[2].setComponents(f+d,l+h,r+n,c+v).normalize();b[3].setComponents(f-d,l-h,r-n,c-v).normalize();b[4].setComponents(f-e,l-k,r-m,c-w).normalize();b[5].setComponents(f+e,l+k,r+m,c+w).normalize();return this},intersectsObject:function(){var a=new Da;return function(b){var c= +b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Da;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)e;e++){var f=d[e];a.x=0g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});Ya.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" "); +Ya.DefaultOrder="XYZ";Object.defineProperties(Ya.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a;this.onChangeCallback()}}});Object.assign(Ya.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z= +c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=R.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],l=e[9],q=e[2],n=e[6],e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-l,e),this._z= +Math.atan2(-f,a)):(this._x=Math.atan2(n,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-q,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(n,-1,1)),.99999>Math.abs(n)?(this._y=Math.atan2(-q,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(q,-1,1)),.99999>Math.abs(q)?(this._x=Math.atan2(n,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"=== +b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-l,k),this._y=Math.atan2(-q,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(n,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-l,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new K;return function(b,c,d){a.makeRotationFromQuaternion(b); +return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new Z;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0=== +b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new p(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Pd.prototype,{set:function(a){this.mask=1<g;g++)if(d[g]===d[(g+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(d=a[f],this.faces.splice(d,1),c=0,e=this.faceVertexUvs.length;ca?b.copy(this.origin):b.copy(this.direction).multiplyScalar(a).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new p;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a= +new p,b=new p,c=new p;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),l=c.dot(this.direction),q=-c.dot(b),n=c.lengthSq(),m=Math.abs(1-k*k);if(0=-p?e<=p?(h=1/m,d*=h,e*=h,k=d*(d+k*e+2*l)+e*(k*d+e+2*q)+n):(e=h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n):(e=-h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n):e<=-p?(d=Math.max(0,-(-k*h+l)),e=0b)return null; +b=Math.sqrt(b-e);e=d-b;d+=b;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){a=this.distanceToPlane(a);return null===a?null:this.at(a,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin); +return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c=1/this.direction.x;var d=1/this.direction.y;var e=1/this.direction.z,f=this.origin;if(0<=c){var g=(a.min.x-f.x)*c;c*=a.max.x-f.x}else g=(a.max.x-f.x)*c,c*=a.min.x-f.x;if(0<=d){var h=(a.min.y-f.y)*d;d*=a.max.y-f.y}else h=(a.max.y-f.y)*d,d*=a.min.y-f.y;if(g>d||h>c)return null;if(h>g||g!==g)g=h;if(da||h>c)return null; +if(h>g||g!==g)g=h;if(ac?null:this.at(0<=g?g:c,b)},intersectsBox:function(){var a=new p;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new p,b=new p,c=new p,d=new p;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null; +g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.origin.applyMatrix4(a);this.direction.transformDirection(a);return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(Mb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start); +this.end.copy(a.end);return this},getCenter:function(a){return(a||new p).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new p).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){b=b||new p;return this.delta(b).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new p,b=new p;return function(c,d){a.subVectors(c, +this.start);b.subVectors(this.end,this.start);c=b.dot(b);c=b.dot(a)/c;d&&(c=R.clamp(c,0,1));return c}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new p;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Qa,{normal:function(){var a=new p;return function(b,c,d,e){e=e||new p; +e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0=b.x+b.y}}()});Object.assign(Qa.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new p,b=new p;return function(){a.subVectors(this.c, +this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new p).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Qa.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new Aa).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Qa.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return Qa.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a= +new Aa,b=[new Mb,new Mb,new Mb],c=new p,d=new p;return function(e,f){f=f||new p;var g=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))f.copy(c);else for(b[0].set(this.a,this.b),b[1].set(this.b,this.c),b[2].set(this.c,this.a),e=0;ec.far?null:{distance:b,point:x.clone(),object:a}}function c(c,d,e,f,l,n,q,t){g.fromBufferAttribute(f,n);h.fromBufferAttribute(f,q);k.fromBufferAttribute(f,t);if(c=b(c,c.material,d,e,g,h,k,w))l&&(m.fromBufferAttribute(l, +n),r.fromBufferAttribute(l,q),u.fromBufferAttribute(l,t),c.uv=a(w,g,h,k,m,r,u)),c.face=new Pa(n,q,t,Qa.normal(g,h,k)),c.faceIndex=n;return c}var d=new K,e=new lb,f=new Da,g=new p,h=new p,k=new p,l=new p,q=new p,n=new p,m=new C,r=new C,u=new C,v=new p,w=new p,x=new p;return function(t,p){var v=this.geometry,x=this.material,z=this.matrixWorld;if(void 0!==x&&(null===v.boundingSphere&&v.computeBoundingSphere(),f.copy(v.boundingSphere),f.applyMatrix4(z),!1!==t.ray.intersectsSphere(f)&&(d.getInverse(z), +e.copy(t.ray).applyMatrix4(d),null===v.boundingBox||!1!==e.intersectsBox(v.boundingBox)))){var y;if(v.isBufferGeometry){var x=v.index,I=v.attributes.position,z=v.attributes.uv,C;if(null!==x){var A=0;for(C=x.count;Af||(f=d.ray.origin.distanceTo(a),fd.far||e.push({distance:f,point:a.clone(),face:null,object:this}))}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});Dc.prototype=Object.assign(Object.create(A.prototype),{constructor:Dc,copy:function(a){A.prototype.copy.call(this, +a,!1);a=a.levels;for(var b=0,c=a.length;b=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;ef||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),md.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}));else for(g=0,v=r.length/3-1;gf||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q), +md.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,l=k.length,g=0;gf||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),md.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry, +this.material)).copy(this)}});ca.prototype=Object.assign(Object.create(ma.prototype),{constructor:ca,isLineSegments:!0});rd.prototype=Object.assign(Object.create(ma.prototype),{constructor:rd,isLineLoop:!0});Ba.prototype=Object.create(Q.prototype);Ba.prototype.constructor=Ba;Ba.prototype.isPointsMaterial=!0;Ba.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Qb.prototype=Object.assign(Object.create(A.prototype), +{constructor:Qb,isPoints:!0,raycast:function(){var a=new K,b=new lb,c=new Da;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(fd.far||e.push({distance:h,distanceToRay:Math.sqrt(f),point:a.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,l=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k); +c.radius+=l;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var l=l/((this.scale.x+this.scale.y+this.scale.z)/3),m=l*l,l=new p;if(h.isBufferGeometry){var n=h.index,h=h.attributes.position.array;if(null!==n)for(var t=n.array,n=0,r=t.length;nc)return null;var d=[],e=[],f=[],g;if(0=h--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}var k= +g;c<=k&&(k=0);g=k+1;c<=g&&(g=0);var l=g+1;c<=l&&(l=0);a:{var m;var n=a[e[k]].x;var p=a[e[k]].y;var r=a[e[g]].x;var u=a[e[g]].y;var v=a[e[l]].x;var w=a[e[l]].y;if(0>=(r-n)*(w-p)-(u-p)*(v-n))var x=!1;else{var z=v-r;var y=w-u;var B=n-v;var C=p-w;var A=r-n;x=u-p;for(m=0;m=-Number.EPSILON&&D>=-Number.EPSILON&&N>=-Number.EPSILON){x= +!1;break a}}}x=!0}}if(x){d.push([a[e[k]],a[e[g]],a[e[l]]]);f.push([e[k],e[g],e[l]]);k=g;for(l=g+1;lNumber.EPSILON){if(0< +q){if(0>p||p>q)return[];k=l*m-k*n;if(0>k||k>q)return[]}else{if(0c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,l]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0d&&(d=c);var e=a+1;e>c&&(e=0);c=f(h[a],h[d],h[e],D[b]);if(!c)return!1;c=D.length-1;d=b-1;0>d&&(d=c);e=b+1;e>c&&(e=0);return(c=f(D[b],D[d],D[e],h[a]))?!0:!1}function d(a,b){var c;for(c=0;ct){console.log('THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!');break}for(m=p;ma;a++)m=b[a].x+":"+b[a].y,m=h[m],void 0!==m&&(b[a]=m);return k.concat()},isClockWise:function(a){return 0>Ha.area(a)}};$a.prototype=Object.create(N.prototype);$a.prototype.constructor=$a;Ga.prototype= +Object.create(D.prototype);Ga.prototype.constructor=Ga;Ga.prototype.getArrays=function(){var a=this.getAttribute("position"),a=a?Array.prototype.slice.call(a.array):[],b=this.getAttribute("uv"),b=b?Array.prototype.slice.call(b.array):[],c=this.index,c=c?Array.prototype.slice.call(c.array):[];return{position:a,uv:b,index:c}};Ga.prototype.addShapeList=function(a,b){var c=a.length;b.arrays=this.getArrays();for(var d=0;dNumber.EPSILON){var k=Math.sqrt(h),l=Math.sqrt(f*f+g*g),h=b.x-e/k;b=b.y+d/k;g=((c.x-g/l-h)*g-(c.y+f/l-b)*f)/(d*g-e*f);f=h+d*g-a.x;d=b+e*g-a.y;e=f*f+d*d;if(2>=e)return new C(f, +d);e=Math.sqrt(e/2)}else a=!1,d>Number.EPSILON?f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(f=-e,e=Math.sqrt(h)):(f=d,d=e,e=Math.sqrt(h/2));return new C(f/e,d/e)}function e(a,b){for(G=a.length;0<=--G;){var c=G;var d=G-1;0>d&&(d=a.length-1);var e,f=A+2*w;for(e=0;eMath.abs(g-k)?[new C(a,1-c),new C(h,1-d),new C(l,1-e),new C(n,1-b)]:[new C(g,1-c),new C(k,1-d),new C(m,1-e),new C(p,1-b)]}};Qc.prototype=Object.create(N.prototype); +Qc.prototype.constructor=Qc;$b.prototype=Object.create(Ga.prototype);$b.prototype.constructor=$b;Rc.prototype=Object.create(N.prototype);Rc.prototype.constructor=Rc;ob.prototype=Object.create(D.prototype);ob.prototype.constructor=ob;Sc.prototype=Object.create(N.prototype);Sc.prototype.constructor=Sc;ac.prototype=Object.create(D.prototype);ac.prototype.constructor=ac;Tc.prototype=Object.create(N.prototype);Tc.prototype.constructor=Tc;bc.prototype=Object.create(D.prototype);bc.prototype.constructor= +bc;cc.prototype=Object.create(N.prototype);cc.prototype.constructor=cc;dc.prototype=Object.create(D.prototype);dc.prototype.constructor=dc;ec.prototype=Object.create(D.prototype);ec.prototype.constructor=ec;pb.prototype=Object.create(N.prototype);pb.prototype.constructor=pb;Sa.prototype=Object.create(D.prototype);Sa.prototype.constructor=Sa;Uc.prototype=Object.create(pb.prototype);Uc.prototype.constructor=Uc;Vc.prototype=Object.create(Sa.prototype);Vc.prototype.constructor=Vc;Wc.prototype=Object.create(N.prototype); +Wc.prototype.constructor=Wc;fc.prototype=Object.create(D.prototype);fc.prototype.constructor=fc;var Ca=Object.freeze({WireframeGeometry:Sb,ParametricGeometry:Hc,ParametricBufferGeometry:Tb,TetrahedronGeometry:Jc,TetrahedronBufferGeometry:Ub,OctahedronGeometry:Kc,OctahedronBufferGeometry:nb,IcosahedronGeometry:Lc,IcosahedronBufferGeometry:Vb,DodecahedronGeometry:Mc,DodecahedronBufferGeometry:Wb,PolyhedronGeometry:Ic,PolyhedronBufferGeometry:qa,TubeGeometry:Nc,TubeBufferGeometry:Xb,TorusKnotGeometry:Oc, +TorusKnotBufferGeometry:Yb,TorusGeometry:Pc,TorusBufferGeometry:Zb,TextGeometry:Qc,TextBufferGeometry:$b,SphereGeometry:Rc,SphereBufferGeometry:ob,RingGeometry:Sc,RingBufferGeometry:ac,PlaneGeometry:Ac,PlaneBufferGeometry:kb,LatheGeometry:Tc,LatheBufferGeometry:bc,ShapeGeometry:cc,ShapeBufferGeometry:dc,ExtrudeGeometry:$a,ExtrudeBufferGeometry:Ga,EdgesGeometry:ec,ConeGeometry:Uc,ConeBufferGeometry:Vc,CylinderGeometry:pb,CylinderBufferGeometry:Sa,CircleGeometry:Wc,CircleBufferGeometry:fc,BoxGeometry:Lb, +BoxBufferGeometry:jb});gc.prototype=Object.create(Q.prototype);gc.prototype.constructor=gc;gc.prototype.isShadowMaterial=!0;hc.prototype=Object.create(oa.prototype);hc.prototype.constructor=hc;hc.prototype.isRawShaderMaterial=!0;Ma.prototype=Object.create(Q.prototype);Ma.prototype.constructor=Ma;Ma.prototype.isMeshStandardMaterial=!0;Ma.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness; +this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap; +this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};qb.prototype=Object.create(Ma.prototype);qb.prototype.constructor=qb;qb.prototype.isMeshPhysicalMaterial= +!0;qb.prototype.copy=function(a){Ma.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ia.prototype=Object.create(Q.prototype);Ia.prototype.constructor=Ia;Ia.prototype.isMeshPhongMaterial=!0;Ia.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity= +a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine= +a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};rb.prototype=Object.create(Ia.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshToonMaterial=!0;rb.prototype.copy=function(a){Ia.prototype.copy.call(this, +a);this.gradientMap=a.gradientMap;return this};sb.prototype=Object.create(Q.prototype);sb.prototype.constructor=sb;sb.prototype.isMeshNormalMaterial=!0;sb.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth; +this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};tb.prototype=Object.create(Q.prototype);tb.prototype.constructor=tb;tb.prototype.isMeshLambertMaterial=!0;tb.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity= +a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ub.prototype=Object.create(O.prototype);ub.prototype.constructor= +ub;ub.prototype.isLineDashedMaterial=!0;ub.prototype.copy=function(a){O.prototype.copy.call(this,a);this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var tg=Object.freeze({ShadowMaterial:gc,SpriteMaterial:Za,RawShaderMaterial:hc,ShaderMaterial:oa,PointsMaterial:Ba,MeshPhysicalMaterial:qb,MeshStandardMaterial:Ma,MeshPhongMaterial:Ia,MeshToonMaterial:rb,MeshNormalMaterial:sb,MeshLambertMaterial:tb,MeshDepthMaterial:Wa,MeshDistanceMaterial:Xa,MeshBasicMaterial:va,LineDashedMaterial:ub, +LineBasicMaterial:O,Material:Q}),jd={enabled:!1,files:{},add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},wa=new Yd,Ta={};Object.assign(Ja.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=jd.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)}, +0),f;if(void 0!==Ta[a])Ta[a].push({onLoad:b,onProgress:c,onError:d});else{var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){c=g[1];var h=!!g[2],g=g[3],g=window.decodeURIComponent(g);h&&(g=window.atob(g));try{var k=(this.responseType||"").toLowerCase();switch(k){case "arraybuffer":case "blob":for(var l=new Uint8Array(g.length),h=0;h=e)break a;else{f=b[1];a=e)break b}d=c;c=0}}for(;c>>1,ab;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),a=this.getValueSize(),this.times=T.arraySlice(c,e,f),this.values=T.arraySlice(this.values,e*a,f*a);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrackPrototype: Invalid value size in track.",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("THREE.KeyframeTrackPrototype: Track is empty.", +this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrackPrototype: Time is not a valid number.",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrackPrototype: Out of order keys.",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&T.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrackPrototype: Value is not a valid number.",this,f,d);a=!1;break}return a},optimize:function(){for(var a, +b,c=this.times,d=this.values,e=this.getValueSize(),f=2302===this.getInterpolation(),g=1,h=c.length-1,k=1;kl.opacity&&(l.transparent=!0);d.setTextures(k);return d.parse(l)}}()});Object.assign(be.prototype, +{load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:kc.prototype.extractUrlBase(a),g=new Ja(this.manager);g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead."); +return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(){return function(a,b){void 0!==a.data&&(a=a.data);a.scale=void 0!==a.scale?1/a.scale:1;var c=new N,d=a,e,f,g,h=d.faces;var k=d.vertices;var l=d.normals,m=d.colors;var n=d.scale;var t=0;if(void 0!==d.uvs){for(e=0;ef;f++){var B=h[r++];var A=y[2*B];B=y[2*B+1];A=new C(A,B);2!==f&&c.faceVertexUvs[e][v].push(A);0!==f&&c.faceVertexUvs[e][v+1].push(A)}}w&&(w=3* +h[r++],u.normal.set(l[w++],l[w++],l[w]),z.normal.copy(u.normal));if(x)for(e=0;4>e;e++)w=3*h[r++],x=new p(l[w++],l[w++],l[w]),2!==e&&u.vertexNormals.push(x),0!==e&&z.vertexNormals.push(x);n&&(n=h[r++],n=m[n],u.color.setHex(n),z.color.setHex(n));if(k)for(e=0;4>e;e++)n=h[r++],n=m[n],2!==e&&u.vertexColors.push(new H(n)),0!==e&&z.vertexColors.push(new H(n));c.faces.push(u);c.faces.push(z)}else{u=new Pa;u.a=h[r++];u.b=h[r++];u.c=h[r++];v&&(v=h[r++],u.materialIndex=v);v=c.faces.length;if(e)for(e=0;ef;f++)B=h[r++],A=y[2*B],B=y[2*B+1],A=new C(A,B),c.faceVertexUvs[e][v].push(A);w&&(w=3*h[r++],u.normal.set(l[w++],l[w++],l[w]));if(x)for(e=0;3>e;e++)w=3*h[r++],x=new p(l[w++],l[w++],l[w]),u.vertexNormals.push(x);n&&(n=h[r++],u.color.setHex(m[n]));if(k)for(e=0;3>e;e++)n=h[r++],u.vertexColors.push(new H(m[n]));c.faces.push(u)}}d=a;r=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(g=0,h=d.skinWeights.length;gg)e=a+1;else if(0b&&(b=0);1Number.EPSILON&&(g.normalize(),c=Math.acos(R.clamp(d[k- +1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(R.clamp(e[0].dot(e[a]),-1,1)),c/=a,0=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate= +!0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;cd;)d+=c;for(;d>c;)d-=c;dc.length-2?c.length-1:a+1],c=c[a>c.length-3?c.length-1:a+2];b.set(Se(d, +e.x,f.x,g.x,c.x),Se(d,e.y,f.y,g.y,c.y));return b};ab.prototype.copy=function(a){S.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;bNumber.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.yh.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=l*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<= +a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Ha.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);b=[];if(1===f.length){var g=f[0];var h=new Cb;h.curves=g.curves;b.push(h);return b}var k=!e(f[0].getPoints()),k=a?!k:k;h=[];var l=[],m=[],n=0;l[n]=void 0;m[n]=[];for(var p=0,r=f.length;pd&&this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d= +0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){Z.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(Ve.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_, +c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(na,{Composite:Ve,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new na.Composite(a,b,c):new na(a,b,c)},sanitizeNodeName:function(a){return a.replace(/\s/g,"_").replace(/[^\w-]/g,"")},parseTrackName:function(){var a=new RegExp("^"+/((?:[\w-]+[\/:])*)/.source+/([\w-\.]+)?/.source+/(?:\.([\w-]+)(?:\[(.+)\])?)?/.source+/\.([\w-]+)(?:\[(.+)\])?/.source+ +"$"),b=["material","materials","bones"];return function(c){var d=a.exec(c);if(!d)throw Error("PropertyBinding: Cannot parse trackName: "+c);var d={nodeName:d[2],objectName:d[3],objectIndex:d[4],propertyName:d[5],propertyIndex:d[6]},e=d.nodeName&&d.nodeName.lastIndexOf(".");if(void 0!==e&&-1!==e){var f=d.nodeName.substring(e+1);-1!==b.indexOf(f)&&(d.nodeName=d.nodeName.substring(0,e),d.objectName=f)}if(null===d.propertyName||0===d.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+ +c);return d}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;if(a.skeleton){var c=function(a){for(var c=0;c=b){var m=b++,n=a[m];c[n.uuid]=l;a[l]=n;c[k]=m;a[m]=h;h=0;for(k=e;h!==k;++h){var n=d[h],p= +n[l];n[l]=n[m];n[m]=p}}}this.nCachedObjects_=b},uncache:function(){for(var a,b,c=this._objects,d=c.length,e=this.nCachedObjects_,f=this._indicesByUUID,g=this._bindings,h=g.length,k=0,l=arguments.length;k!==l;++k){b=arguments[k].uuid;var m=f[b];if(void 0!==m)if(delete f[b],mb||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0], +b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d; +-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time= +b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}});Object.assign(Ye.prototype,ja.prototype, +{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings;a=a._interpolants;var g=c.uuid,h=this._bindingsByRootAndName,k=h[g];void 0===k&&(k={},h[g]=k);for(h=0;h!==e;++h){var l=d[h],m=l.name,n=k[m];if(void 0===n){n=f[h];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,g,m));continue}n=new je(na.create(c,m,b&&b._propertyBindings[h].binding.parsedPath),l.ValueTypeName,l.getValueSize());++n.referenceCount;this._addInactiveBinding(n, +g,m)}f[h]=n;a[h].resultBuffer=n.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings, +c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length}, +get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&aMath.abs(b)&&(b=1E-8);this.scale.set(.5*this.size,.5*this.size,b);this.lookAt(this.plane.normal);A.prototype.updateMatrixWorld.call(this,a)};var Ld,pe;Eb.prototype=Object.create(A.prototype);Eb.prototype.constructor=Eb;Eb.prototype.setDirection=function(){var a=new p,b;return function(c){.99999c.y?this.quaternion.set(1, +0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Eb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Eb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};hd.prototype=Object.create(ca.prototype);hd.prototype.constructor=hd;var Nd=new p, +te=new qe,ue=new qe,ve=new qe;ya.prototype=Object.create(S.prototype);ya.prototype.constructor=ya;ya.prototype.isCatmullRomCurve3=!0;ya.prototype.getPoint=function(a,b){b=b||new p;var c=this.points,d=c.length;a*=d-(this.closed?0:1);var e=Math.floor(a);a-=e;this.closed?e+=0e&&(e=1);1E-4>d&&(d=e);1E-4>k&&(k=e);te.initNonuniformCatmullRom(f.x,g.x,h.x,c.x,d,e,k);ue.initNonuniformCatmullRom(f.y,g.y,h.y,c.y,d,e,k);ve.initNonuniformCatmullRom(f.z,g.z,h.z,c.z,d,e,k)}else"catmullrom"===this.curveType&&(te.initCatmullRom(f.x,g.x,h.x, +c.x,this.tension),ue.initCatmullRom(f.y,g.y,h.y,c.y,this.tension),ve.initCatmullRom(f.z,g.z,h.z,c.z,this.tension));b.set(te.calc(a),ue.calc(a),ve.calc(a));return b};ya.prototype.copy=function(a){S.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b 0) { + for (var i = (this.length >> 1); i >= 0; i--) this._down(i); + } +} + +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +TinyQueue.prototype = { + + push: function (item) { + this.data.push(item); + this.length++; + this._up(this.length - 1); + }, + + pop: function () { + if (this.length === 0) return undefined; + var top = this.data[0]; + this.length--; + if (this.length > 0) { + this.data[0] = this.data[this.length]; + this._down(0); + } + this.data.pop(); + return top; + }, + + peek: function () { + return this.data[0]; + }, + + _up: function (pos) { + var data = this.data; + var compare = this.compare; + var item = data[pos]; + + while (pos > 0) { + var parent = (pos - 1) >> 1; + var current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + }, + + _down: function (pos) { + var data = this.data; + var compare = this.compare; + var len = this.length; + var halfLen = len >> 1; + var item = data[pos]; + + while (pos < halfLen) { + var left = (pos << 1) + 1; + var right = left + 1; + var best = data[left]; + + if (right < len && compare(data[right], best) < 0) { + left = right; + best = data[right]; + } + if (compare(best, item) >= 0) break; + + data[pos] = best; + pos = left; + } + + data[pos] = item; + } +}; + +},{}],242:[function(require,module,exports){ +// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `exports` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var + push = ArrayProto.push, + slice = ArrayProto.slice, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind, + nativeCreate = Object.create; + + // Naked function reference for surrogate-prototype-swapping. + var Ctor = function(){}; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.8.3'; + + // Internal function that returns an efficient (for current engines) version + // of the passed-in callback, to be repeatedly applied in other Underscore + // functions. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + return func.apply(context, arguments); + }; + }; + + // A mostly-internal function to generate callbacks that can be applied + // to each element in a collection, returning the desired result — either + // identity, an arbitrary callback, a property matcher, or a property accessor. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + Ctor.prototype = null; + return result; + }; + + var property = function(key) { + return function(obj) { + return obj == null ? void 0 : obj[key]; + }; + }; + + // Helper for collection methods to determine whether a collection + // should be iterated as an array or as an object + // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + var length = getLength(collection); + return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; + }; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles raw objects in addition to array-likes. Treats all + // sparse array-likes as if they were dense. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + return iterator(obj, iteratee, memo, keys, index, length); + }; + } + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. + _.reduce = _.foldl = _.inject = createReduce(1); + + // The right-associative version of reduce, also known as `foldr`. + _.reduceRight = _.foldr = createReduce(-1); + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, predicate, context) { + var key; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) return obj[key]; + }; + + // Return all the elements that pass a truth test. + // Aliased as `select`. + _.filter = _.select = function(obj, predicate, context) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, predicate, context) { + return _.filter(obj, _.negate(cb(predicate)), context); + }; + + // Determine whether all of the elements match a truth test. + // Aliased as `all`. + _.every = _.all = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + return false; + }; + + // Determine if the array or object contains a given item (using `===`). + // Aliased as `includes` and `include`. + _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + if (typeof fromIndex != 'number' || guard) fromIndex = 0; + return _.indexOf(obj, item, fromIndex) >= 0; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + return func == null ? func : func.apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, _.property(key)); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs) { + return _.filter(obj, _.matcher(attrs)); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.find(obj, _.matcher(attrs)); + }; + + // Return the maximum element (or element-based computation). + _.max = function(obj, iteratee, context) { + var result = -Infinity, lastComputed = -Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Shuffle a collection, using the modern version of the + // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). + _.shuffle = function(obj) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + return shuffled; + }; + + // Sample **n** random values from a collection. + // If **n** is not specified, returns a single random element. + // The internal `guard` argument allows it to work with `map`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + return _.shuffle(obj).slice(0, Math.max(0, n)); + }; + + // Sort the object's values by a criterion produced by an iteratee. + _.sortBy = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + return result; + }; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = group(function(result, value, key) { + if (_.has(result, key)) result[key].push(value); else result[key] = [value]; + }); + + // Indexes the object's values by a criterion, similar to `groupBy`, but for + // when you know that your index values will be unique. + _.indexBy = group(function(result, value, key) { + result[key] = value; + }); + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = group(function(result, value, key) { + if (_.has(result, key)) result[key]++; else result[key] = 1; + }); + + // Safely create a real, live array from anything iterable. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; @@ -14064,129 +18907,22 @@ this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas" } }.call(this)); -},{}],159:[function(require,module,exports){ -/* - * Copyright (C) 2008 Apple Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Ported from Webkit - * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h - */ - -module.exports = UnitBezier; - -function UnitBezier(p1x, p1y, p2x, p2y) { - // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). - this.cx = 3.0 * p1x; - this.bx = 3.0 * (p2x - p1x) - this.cx; - this.ax = 1.0 - this.cx - this.bx; - - this.cy = 3.0 * p1y; - this.by = 3.0 * (p2y - p1y) - this.cy; - this.ay = 1.0 - this.cy - this.by; - - this.p1x = p1x; - this.p1y = p2y; - this.p2x = p2x; - this.p2y = p2y; -} - -UnitBezier.prototype.sampleCurveX = function(t) { - // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. - return ((this.ax * t + this.bx) * t + this.cx) * t; -}; - -UnitBezier.prototype.sampleCurveY = function(t) { - return ((this.ay * t + this.by) * t + this.cy) * t; -}; - -UnitBezier.prototype.sampleCurveDerivativeX = function(t) { - return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; -}; - -UnitBezier.prototype.solveCurveX = function(x, epsilon) { - if (typeof epsilon === 'undefined') epsilon = 1e-6; - - var t0, t1, t2, x2, i; - - // First try a few iterations of Newton's method -- normally very fast. - for (t2 = x, i = 0; i < 8; i++) { - - x2 = this.sampleCurveX(t2) - x; - if (Math.abs(x2) < epsilon) return t2; - - var d2 = this.sampleCurveDerivativeX(t2); - if (Math.abs(d2) < 1e-6) break; - - t2 = t2 - x2 / d2; - } - - // Fall back to the bisection method for reliability. - t0 = 0.0; - t1 = 1.0; - t2 = x; - - if (t2 < t0) return t0; - if (t2 > t1) return t1; - - while (t0 < t1) { - - x2 = this.sampleCurveX(t2); - if (Math.abs(x2 - x) < epsilon) return t2; - - if (x > x2) { - t0 = t2; - } else { - t1 = t2; - } - - t2 = (t1 - t0) * 0.5 + t0; - } - - // Failure. - return t2; -}; - -UnitBezier.prototype.solve = function(x, epsilon) { - return this.sampleCurveY(this.solveCurveX(x, epsilon)); -}; - -},{}],160:[function(require,module,exports){ +},{}],243:[function(require,module,exports){ var createElement = require("./vdom/create-element.js") module.exports = createElement -},{"./vdom/create-element.js":166}],161:[function(require,module,exports){ +},{"./vdom/create-element.js":249}],244:[function(require,module,exports){ var diff = require("./vtree/diff.js") module.exports = diff -},{"./vtree/diff.js":186}],162:[function(require,module,exports){ +},{"./vtree/diff.js":269}],245:[function(require,module,exports){ var h = require("./virtual-hyperscript/index.js") module.exports = h -},{"./virtual-hyperscript/index.js":173}],163:[function(require,module,exports){ +},{"./virtual-hyperscript/index.js":256}],246:[function(require,module,exports){ var diff = require("./diff.js") var patch = require("./patch.js") var h = require("./h.js") @@ -14203,12 +18939,12 @@ module.exports = { VText: VText } -},{"./create-element.js":160,"./diff.js":161,"./h.js":162,"./patch.js":164,"./vnode/vnode.js":182,"./vnode/vtext.js":184}],164:[function(require,module,exports){ +},{"./create-element.js":243,"./diff.js":244,"./h.js":245,"./patch.js":247,"./vnode/vnode.js":265,"./vnode/vtext.js":267}],247:[function(require,module,exports){ var patch = require("./vdom/patch.js") module.exports = patch -},{"./vdom/patch.js":169}],165:[function(require,module,exports){ +},{"./vdom/patch.js":252}],248:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("../vnode/is-vhook.js") @@ -14307,7 +19043,7 @@ function getPrototype(value) { } } -},{"../vnode/is-vhook.js":177,"is-object":18}],166:[function(require,module,exports){ +},{"../vnode/is-vhook.js":260,"is-object":20}],249:[function(require,module,exports){ var document = require("global/document") var applyProperties = require("./apply-properties") @@ -14355,7 +19091,7 @@ function createElement(vnode, opts) { return node } -},{"../vnode/handle-thunk.js":175,"../vnode/is-vnode.js":178,"../vnode/is-vtext.js":179,"../vnode/is-widget.js":180,"./apply-properties":165,"global/document":14}],167:[function(require,module,exports){ +},{"../vnode/handle-thunk.js":258,"../vnode/is-vnode.js":261,"../vnode/is-vtext.js":262,"../vnode/is-widget.js":263,"./apply-properties":248,"global/document":16}],250:[function(require,module,exports){ // Maps a virtual DOM tree onto a real DOM tree in an efficient manner. // We don't want to read all of the DOM nodes in the tree so we use // the in-order tree indexing to eliminate recursion down certain branches. @@ -14442,7 +19178,7 @@ function ascending(a, b) { return a > b ? 1 : -1 } -},{}],168:[function(require,module,exports){ +},{}],251:[function(require,module,exports){ var applyProperties = require("./apply-properties") var isWidget = require("../vnode/is-widget.js") @@ -14595,7 +19331,7 @@ function replaceRoot(oldRoot, newRoot) { return newRoot; } -},{"../vnode/is-widget.js":180,"../vnode/vpatch.js":183,"./apply-properties":165,"./update-widget":170}],169:[function(require,module,exports){ +},{"../vnode/is-widget.js":263,"../vnode/vpatch.js":266,"./apply-properties":248,"./update-widget":253}],252:[function(require,module,exports){ var document = require("global/document") var isArray = require("x-is-array") @@ -14677,7 +19413,7 @@ function patchIndices(patches) { return indices } -},{"./create-element":166,"./dom-index":167,"./patch-op":168,"global/document":14,"x-is-array":205}],170:[function(require,module,exports){ +},{"./create-element":249,"./dom-index":250,"./patch-op":251,"global/document":16,"x-is-array":288}],253:[function(require,module,exports){ var isWidget = require("../vnode/is-widget.js") module.exports = updateWidget @@ -14694,7 +19430,7 @@ function updateWidget(a, b) { return false } -},{"../vnode/is-widget.js":180}],171:[function(require,module,exports){ +},{"../vnode/is-widget.js":263}],254:[function(require,module,exports){ 'use strict'; var EvStore = require('ev-store'); @@ -14723,7 +19459,7 @@ EvHook.prototype.unhook = function(node, propertyName) { es[propName] = undefined; }; -},{"ev-store":7}],172:[function(require,module,exports){ +},{"ev-store":9}],255:[function(require,module,exports){ 'use strict'; module.exports = SoftSetHook; @@ -14742,7 +19478,7 @@ SoftSetHook.prototype.hook = function (node, propertyName) { } }; -},{}],173:[function(require,module,exports){ +},{}],256:[function(require,module,exports){ 'use strict'; var isArray = require('x-is-array'); @@ -14881,7 +19617,7 @@ function errorString(obj) { } } -},{"../vnode/is-thunk":176,"../vnode/is-vhook":177,"../vnode/is-vnode":178,"../vnode/is-vtext":179,"../vnode/is-widget":180,"../vnode/vnode.js":182,"../vnode/vtext.js":184,"./hooks/ev-hook.js":171,"./hooks/soft-set-hook.js":172,"./parse-tag.js":174,"x-is-array":205}],174:[function(require,module,exports){ +},{"../vnode/is-thunk":259,"../vnode/is-vhook":260,"../vnode/is-vnode":261,"../vnode/is-vtext":262,"../vnode/is-widget":263,"../vnode/vnode.js":265,"../vnode/vtext.js":267,"./hooks/ev-hook.js":254,"./hooks/soft-set-hook.js":255,"./parse-tag.js":257,"x-is-array":288}],257:[function(require,module,exports){ 'use strict'; var split = require('browser-split'); @@ -14937,7 +19673,7 @@ function parseTag(tag, props) { return props.namespace ? tagName : tagName.toUpperCase(); } -},{"browser-split":3}],175:[function(require,module,exports){ +},{"browser-split":5}],258:[function(require,module,exports){ var isVNode = require("./is-vnode") var isVText = require("./is-vtext") var isWidget = require("./is-widget") @@ -14979,14 +19715,14 @@ function renderThunk(thunk, previous) { return renderedThunk } -},{"./is-thunk":176,"./is-vnode":178,"./is-vtext":179,"./is-widget":180}],176:[function(require,module,exports){ +},{"./is-thunk":259,"./is-vnode":261,"./is-vtext":262,"./is-widget":263}],259:[function(require,module,exports){ module.exports = isThunk function isThunk(t) { return t && t.type === "Thunk" } -},{}],177:[function(require,module,exports){ +},{}],260:[function(require,module,exports){ module.exports = isHook function isHook(hook) { @@ -14995,7 +19731,7 @@ function isHook(hook) { typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook")) } -},{}],178:[function(require,module,exports){ +},{}],261:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualNode @@ -15004,7 +19740,7 @@ function isVirtualNode(x) { return x && x.type === "VirtualNode" && x.version === version } -},{"./version":181}],179:[function(require,module,exports){ +},{"./version":264}],262:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualText @@ -15013,17 +19749,17 @@ function isVirtualText(x) { return x && x.type === "VirtualText" && x.version === version } -},{"./version":181}],180:[function(require,module,exports){ +},{"./version":264}],263:[function(require,module,exports){ module.exports = isWidget function isWidget(w) { return w && w.type === "Widget" } -},{}],181:[function(require,module,exports){ +},{}],264:[function(require,module,exports){ module.exports = "2" -},{}],182:[function(require,module,exports){ +},{}],265:[function(require,module,exports){ var version = require("./version") var isVNode = require("./is-vnode") var isWidget = require("./is-widget") @@ -15097,7 +19833,7 @@ function VirtualNode(tagName, properties, children, key, namespace) { VirtualNode.prototype.version = version VirtualNode.prototype.type = "VirtualNode" -},{"./is-thunk":176,"./is-vhook":177,"./is-vnode":178,"./is-widget":180,"./version":181}],183:[function(require,module,exports){ +},{"./is-thunk":259,"./is-vhook":260,"./is-vnode":261,"./is-widget":263,"./version":264}],266:[function(require,module,exports){ var version = require("./version") VirtualPatch.NONE = 0 @@ -15121,7 +19857,7 @@ function VirtualPatch(type, vNode, patch) { VirtualPatch.prototype.version = version VirtualPatch.prototype.type = "VirtualPatch" -},{"./version":181}],184:[function(require,module,exports){ +},{"./version":264}],267:[function(require,module,exports){ var version = require("./version") module.exports = VirtualText @@ -15133,7 +19869,7 @@ function VirtualText(text) { VirtualText.prototype.version = version VirtualText.prototype.type = "VirtualText" -},{"./version":181}],185:[function(require,module,exports){ +},{"./version":264}],268:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("../vnode/is-vhook") @@ -15193,7 +19929,7 @@ function getPrototype(value) { } } -},{"../vnode/is-vhook":177,"is-object":18}],186:[function(require,module,exports){ +},{"../vnode/is-vhook":260,"is-object":20}],269:[function(require,module,exports){ var isArray = require("x-is-array") var VPatch = require("../vnode/vpatch") @@ -15622,7 +20358,7 @@ function appendPatch(apply, patch) { } } -},{"../vnode/handle-thunk":175,"../vnode/is-thunk":176,"../vnode/is-vnode":178,"../vnode/is-vtext":179,"../vnode/is-widget":180,"../vnode/vpatch":183,"./diff-props":185,"x-is-array":205}],187:[function(require,module,exports){ +},{"../vnode/handle-thunk":258,"../vnode/is-thunk":259,"../vnode/is-vnode":261,"../vnode/is-vtext":262,"../vnode/is-widget":263,"../vnode/vpatch":266,"./diff-props":268,"x-is-array":288}],270:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -15641,7 +20377,7 @@ define(function (require) { }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); -},{"./Scheduler":188,"./env":200,"./makePromise":202}],188:[function(require,module,exports){ +},{"./Scheduler":271,"./env":283,"./makePromise":285}],271:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -15723,7 +20459,7 @@ define(function() { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],189:[function(require,module,exports){ +},{}],272:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -15751,7 +20487,7 @@ define(function() { return TimeoutError; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],190:[function(require,module,exports){ +},{}],273:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -15808,7 +20544,7 @@ define(function() { -},{}],191:[function(require,module,exports){ +},{}],274:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16050,13 +20786,23 @@ define(function(require) { } function settleOne(p) { - var h = Promise._handler(p); - if(h.state() === 0) { + // Optimize the case where we get an already-resolved when.js promise + // by extracting its state: + var handler; + if (p instanceof Promise) { + // This is our own Promise type and we can reach its handler internals: + handler = p._handler.join(); + } + if((handler && handler.state() === 0) || !handler) { + // Either still pending, or not a Promise at all: return toPromise(p).then(state.fulfilled, state.rejected); } - h._unreport(); - return state.inspect(h); + // The promise is our own, but it is already resolved. Take a shortcut. + // Since we're not actually handling the resolution, we need to disable + // rejection reporting. + handler._unreport(); + return state.inspect(handler); } /** @@ -16099,7 +20845,7 @@ define(function(require) { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); -},{"../apply":190,"../state":203}],192:[function(require,module,exports){ +},{"../apply":273,"../state":286}],275:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16261,7 +21007,7 @@ define(function() { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],193:[function(require,module,exports){ +},{}],276:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16290,7 +21036,7 @@ define(function() { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],194:[function(require,module,exports){ +},{}],277:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16312,7 +21058,7 @@ define(function(require) { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); -},{"../state":203}],195:[function(require,module,exports){ +},{"../state":286}],278:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16379,7 +21125,7 @@ define(function() { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],196:[function(require,module,exports){ +},{}],279:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16405,7 +21151,7 @@ define(function() { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],197:[function(require,module,exports){ +},{}],280:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16485,7 +21231,7 @@ define(function(require) { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); -},{"../TimeoutError":189,"../env":200}],198:[function(require,module,exports){ +},{"../TimeoutError":272,"../env":283}],281:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16573,7 +21319,7 @@ define(function(require) { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); -},{"../env":200,"../format":201}],199:[function(require,module,exports){ +},{"../env":283,"../format":284}],282:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16613,7 +21359,7 @@ define(function() { }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],200:[function(require,module,exports){ +},{}],283:[function(require,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ @@ -16664,8 +21410,8 @@ define(function(require) { } function hasMutationObserver () { - return (typeof MutationObserver === 'function' && MutationObserver) || - (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver); + return (typeof MutationObserver !== 'undefined' && MutationObserver) || + (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver); } function initMutationObserver(MutationObserver) { @@ -16691,7 +21437,7 @@ define(function(require) { }).call(this,require('_process')) -},{"_process":4}],201:[function(require,module,exports){ +},{"_process":6}],284:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -16749,7 +21495,7 @@ define(function() { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],202:[function(require,module,exports){ +},{}],285:[function(require,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ @@ -17635,6 +22381,28 @@ define(function() { function noop() {} + function hasCustomEvent() { + if(typeof CustomEvent === 'function') { + try { + var ev = new CustomEvent('unhandledRejection'); + return ev instanceof CustomEvent; + } catch (ignoredException) {} + } + return false; + } + + function hasInternetExplorerCustomEvent() { + if(typeof document !== 'undefined' && typeof document.createEvent === 'function') { + try { + // Try to create one event to make sure it's supported + var ev = document.createEvent('CustomEvent'); + ev.initCustomEvent('eventType', false, true, {}); + return true; + } catch (ignoredException) {} + } + return false; + } + function initEmitRejection() { /*global process, self, CustomEvent*/ if(typeof process !== 'undefined' && process !== null @@ -17648,15 +22416,9 @@ define(function() { ? process.emit(type, rejection.value, rejection) : process.emit(type, rejection); }; - } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') { - return (function(noop, self, CustomEvent) { - var hasCustomEvent = false; - try { - var ev = new CustomEvent('unhandledRejection'); - hasCustomEvent = ev instanceof CustomEvent; - } catch (e) {} - - return !hasCustomEvent ? noop : function(type, rejection) { + } else if(typeof self !== 'undefined' && hasCustomEvent()) { + return (function (self, CustomEvent) { + return function (type, rejection) { var ev = new CustomEvent(type, { detail: { reason: rejection.value, @@ -17668,7 +22430,19 @@ define(function() { return !self.dispatchEvent(ev); }; - }(noop, self, CustomEvent)); + }(self, CustomEvent)); + } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) { + return (function(self, document) { + return function(type, rejection) { + var ev = document.createEvent('CustomEvent'); + ev.initCustomEvent(type, false, true, { + reason: rejection.value, + key: rejection + }); + + return !self.dispatchEvent(ev); + }; + }(self, document)); } return noop; @@ -17681,7 +22455,7 @@ define(function() { }).call(this,require('_process')) -},{"_process":4}],203:[function(require,module,exports){ +},{"_process":6}],286:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ @@ -17718,7 +22492,7 @@ define(function() { }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); -},{}],204:[function(require,module,exports){ +},{}],287:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @@ -17948,7 +22722,7 @@ define(function (require) { }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); -},{"./lib/Promise":187,"./lib/TimeoutError":189,"./lib/apply":190,"./lib/decorators/array":191,"./lib/decorators/flow":192,"./lib/decorators/fold":193,"./lib/decorators/inspect":194,"./lib/decorators/iterate":195,"./lib/decorators/progress":196,"./lib/decorators/timed":197,"./lib/decorators/unhandledRejection":198,"./lib/decorators/with":199}],205:[function(require,module,exports){ +},{"./lib/Promise":270,"./lib/TimeoutError":272,"./lib/apply":273,"./lib/decorators/array":274,"./lib/decorators/flow":275,"./lib/decorators/fold":276,"./lib/decorators/inspect":277,"./lib/decorators/iterate":278,"./lib/decorators/progress":279,"./lib/decorators/timed":280,"./lib/decorators/unhandledRejection":281,"./lib/decorators/with":282}],288:[function(require,module,exports){ var nativeIsArray = Array.isArray var toString = Object.prototype.toString @@ -17958,17 +22732,30 @@ function isArray(obj) { return toString.call(obj) === "[object Array]" } -},{}],206:[function(require,module,exports){ +},{}],289:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var APIv3_1 = require("./api/APIv3"); exports.APIv3 = APIv3_1.APIv3; +var ModelCreator_1 = require("./api/ModelCreator"); +exports.ModelCreator = ModelCreator_1.ModelCreator; -},{"./api/APIv3":217}],207:[function(require,module,exports){ +},{"./api/APIv3":302,"./api/ModelCreator":303}],290:[function(require,module,exports){ "use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); var Component_1 = require("./component/Component"); exports.Component = Component_1.Component; var ComponentService_1 = require("./component/ComponentService"); exports.ComponentService = ComponentService_1.ComponentService; +var HandlerBase_1 = require("./component/utils/HandlerBase"); +exports.HandlerBase = HandlerBase_1.HandlerBase; +var MeshFactory_1 = require("./component/utils/MeshFactory"); +exports.MeshFactory = MeshFactory_1.MeshFactory; +var MeshScene_1 = require("./component/utils/MeshScene"); +exports.MeshScene = MeshScene_1.MeshScene; var AttributionComponent_1 = require("./component/AttributionComponent"); exports.AttributionComponent = AttributionComponent_1.AttributionComponent; var BackgroundComponent_1 = require("./component/BackgroundComponent"); @@ -17989,16 +22776,42 @@ var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer; var ImageComponent_1 = require("./component/ImageComponent"); exports.ImageComponent = ImageComponent_1.ImageComponent; -var KeyboardComponent_1 = require("./component/KeyboardComponent"); +var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent"); exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent; +var KeyPlayHandler_1 = require("./component/keyboard/KeyPlayHandler"); +exports.KeyPlayHandler = KeyPlayHandler_1.KeyPlayHandler; +var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler"); +exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler; +var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler"); +exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler; +var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler"); +exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler; var LoadingComponent_1 = require("./component/LoadingComponent"); exports.LoadingComponent = LoadingComponent_1.LoadingComponent; -var Marker_1 = require("./component/marker/Marker"); +var Marker_1 = require("./component/marker/marker/Marker"); exports.Marker = Marker_1.Marker; var MarkerComponent_1 = require("./component/marker/MarkerComponent"); exports.MarkerComponent = MarkerComponent_1.MarkerComponent; -var MouseComponent_1 = require("./component/MouseComponent"); +var MarkerScene_1 = require("./component/marker/MarkerScene"); +exports.MarkerScene = MarkerScene_1.MarkerScene; +var MarkerSet_1 = require("./component/marker/MarkerSet"); +exports.MarkerSet = MarkerSet_1.MarkerSet; +var MouseComponent_1 = require("./component/mouse/MouseComponent"); exports.MouseComponent = MouseComponent_1.MouseComponent; +var BounceHandler_1 = require("./component/mouse/BounceHandler"); +exports.BounceHandler = BounceHandler_1.BounceHandler; +var DragPanHandler_1 = require("./component/mouse/DragPanHandler"); +exports.DragPanHandler = DragPanHandler_1.DragPanHandler; +var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler"); +exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler; +var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler"); +exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler; +var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler"); +exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler; +var Popup_1 = require("./component/popup/popup/Popup"); +exports.Popup = Popup_1.Popup; +var PopupComponent_1 = require("./component/popup/PopupComponent"); +exports.PopupComponent = PopupComponent_1.PopupComponent; var NavigationComponent_1 = require("./component/NavigationComponent"); exports.NavigationComponent = NavigationComponent_1.NavigationComponent; var RouteComponent_1 = require("./component/RouteComponent"); @@ -18007,28 +22820,44 @@ var SequenceComponent_1 = require("./component/sequence/SequenceComponent"); exports.SequenceComponent = SequenceComponent_1.SequenceComponent; var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer"); exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer; -var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction"); -exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction; +var SequenceMode_1 = require("./component/sequence/SequenceMode"); +exports.SequenceMode = SequenceMode_1.SequenceMode; var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent"); exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent; -var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory"); -exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory; var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer"); exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer; -var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene"); -exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene; -var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders"); -exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders; -var SimpleMarker_1 = require("./component/marker/SimpleMarker"); +var Shaders_1 = require("./component/shaders/Shaders"); +exports.Shaders = Shaders_1.Shaders; +var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker"); exports.SimpleMarker = SimpleMarker_1.SimpleMarker; -var SliderComponent_1 = require("./component/imageplane/SliderComponent"); +var CircleMarker_1 = require("./component/marker/marker/CircleMarker"); +exports.CircleMarker = CircleMarker_1.CircleMarker; +var SliderComponent_1 = require("./component/slider/SliderComponent"); exports.SliderComponent = SliderComponent_1.SliderComponent; +var SliderDOMRenderer_1 = require("./component/slider/SliderDOMRenderer"); +exports.SliderDOMRenderer = SliderDOMRenderer_1.SliderDOMRenderer; +var SliderGLRenderer_1 = require("./component/slider/SliderGLRenderer"); +exports.SliderGLRenderer = SliderGLRenderer_1.SliderGLRenderer; var StatsComponent_1 = require("./component/StatsComponent"); exports.StatsComponent = StatsComponent_1.StatsComponent; +var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase"); +exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase; +var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase"); +exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase; +var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler"); +exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler; +var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler"); +exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler; +var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler"); +exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler; +var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler"); +exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler; +var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler"); +exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler; +var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler"); +exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler; var Tag_1 = require("./component/tag/tag/Tag"); exports.Tag = Tag_1.Tag; -var Alignment_1 = require("./component/tag/tag/Alignment"); -exports.Alignment = Alignment_1.Alignment; var OutlineTag_1 = require("./component/tag/tag/OutlineTag"); exports.OutlineTag = OutlineTag_1.OutlineTag; var RenderTag_1 = require("./component/tag/tag/RenderTag"); @@ -18047,10 +22876,12 @@ var TagCreator_1 = require("./component/tag/TagCreator"); exports.TagCreator = TagCreator_1.TagCreator; var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer"); exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer; -var TagGLRenderer_1 = require("./component/tag/TagGLRenderer"); -exports.TagGLRenderer = TagGLRenderer_1.TagGLRenderer; +var TagMode_1 = require("./component/tag/TagMode"); +exports.TagMode = TagMode_1.TagMode; var TagOperation_1 = require("./component/tag/TagOperation"); exports.TagOperation = TagOperation_1.TagOperation; +var TagScene_1 = require("./component/tag/TagScene"); +exports.TagScene = TagScene_1.TagScene; var TagSet_1 = require("./component/tag/TagSet"); exports.TagSet = TagSet_1.TagSet; var Geometry_1 = require("./component/tag/geometry/Geometry"); @@ -18065,9 +22896,13 @@ var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry"); exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry; var GeometryTagError_1 = require("./component/tag/error/GeometryTagError"); exports.GeometryTagError = GeometryTagError_1.GeometryTagError; +var ZoomComponent_1 = require("./component/zoom/ZoomComponent"); +exports.ZoomComponent = ZoomComponent_1.ZoomComponent; +__export(require("./component/interfaces/interfaces")); -},{"./component/AttributionComponent":218,"./component/BackgroundComponent":219,"./component/BearingComponent":220,"./component/CacheComponent":221,"./component/Component":222,"./component/ComponentService":223,"./component/CoverComponent":224,"./component/DebugComponent":225,"./component/ImageComponent":226,"./component/KeyboardComponent":227,"./component/LoadingComponent":228,"./component/MouseComponent":229,"./component/NavigationComponent":230,"./component/RouteComponent":231,"./component/StatsComponent":232,"./component/direction/DirectionComponent":233,"./component/direction/DirectionDOMCalculator":234,"./component/direction/DirectionDOMRenderer":235,"./component/imageplane/ImagePlaneComponent":236,"./component/imageplane/ImagePlaneFactory":237,"./component/imageplane/ImagePlaneGLRenderer":238,"./component/imageplane/ImagePlaneScene":239,"./component/imageplane/ImagePlaneShaders":240,"./component/imageplane/SliderComponent":241,"./component/marker/Marker":242,"./component/marker/MarkerComponent":243,"./component/marker/SimpleMarker":244,"./component/sequence/SequenceComponent":245,"./component/sequence/SequenceDOMInteraction":246,"./component/sequence/SequenceDOMRenderer":247,"./component/tag/TagComponent":249,"./component/tag/TagCreator":250,"./component/tag/TagDOMRenderer":251,"./component/tag/TagGLRenderer":252,"./component/tag/TagOperation":253,"./component/tag/TagSet":254,"./component/tag/error/GeometryTagError":255,"./component/tag/geometry/Geometry":256,"./component/tag/geometry/PointGeometry":257,"./component/tag/geometry/PolygonGeometry":258,"./component/tag/geometry/RectGeometry":259,"./component/tag/geometry/VertexGeometry":260,"./component/tag/tag/Alignment":261,"./component/tag/tag/OutlineCreateTag":262,"./component/tag/tag/OutlineRenderTag":263,"./component/tag/tag/OutlineTag":264,"./component/tag/tag/RenderTag":265,"./component/tag/tag/SpotRenderTag":266,"./component/tag/tag/SpotTag":267,"./component/tag/tag/Tag":268}],208:[function(require,module,exports){ +},{"./component/AttributionComponent":304,"./component/BackgroundComponent":305,"./component/BearingComponent":306,"./component/CacheComponent":307,"./component/Component":308,"./component/ComponentService":309,"./component/CoverComponent":310,"./component/DebugComponent":311,"./component/ImageComponent":312,"./component/LoadingComponent":313,"./component/NavigationComponent":314,"./component/RouteComponent":315,"./component/StatsComponent":316,"./component/direction/DirectionComponent":317,"./component/direction/DirectionDOMCalculator":318,"./component/direction/DirectionDOMRenderer":319,"./component/imageplane/ImagePlaneComponent":320,"./component/imageplane/ImagePlaneGLRenderer":321,"./component/interfaces/interfaces":324,"./component/keyboard/KeyPlayHandler":325,"./component/keyboard/KeySequenceNavigationHandler":326,"./component/keyboard/KeySpatialNavigationHandler":327,"./component/keyboard/KeyZoomHandler":328,"./component/keyboard/KeyboardComponent":329,"./component/marker/MarkerComponent":331,"./component/marker/MarkerScene":332,"./component/marker/MarkerSet":333,"./component/marker/marker/CircleMarker":334,"./component/marker/marker/Marker":335,"./component/marker/marker/SimpleMarker":336,"./component/mouse/BounceHandler":337,"./component/mouse/DoubleClickZoomHandler":338,"./component/mouse/DragPanHandler":339,"./component/mouse/MouseComponent":340,"./component/mouse/ScrollZoomHandler":341,"./component/mouse/TouchZoomHandler":342,"./component/popup/PopupComponent":344,"./component/popup/popup/Popup":345,"./component/sequence/SequenceComponent":346,"./component/sequence/SequenceDOMRenderer":347,"./component/sequence/SequenceMode":348,"./component/shaders/Shaders":349,"./component/slider/SliderComponent":350,"./component/slider/SliderDOMRenderer":351,"./component/slider/SliderGLRenderer":352,"./component/tag/TagComponent":354,"./component/tag/TagCreator":355,"./component/tag/TagDOMRenderer":356,"./component/tag/TagMode":357,"./component/tag/TagOperation":358,"./component/tag/TagScene":359,"./component/tag/TagSet":360,"./component/tag/error/GeometryTagError":361,"./component/tag/geometry/Geometry":362,"./component/tag/geometry/PointGeometry":363,"./component/tag/geometry/PolygonGeometry":364,"./component/tag/geometry/RectGeometry":365,"./component/tag/geometry/VertexGeometry":366,"./component/tag/handlers/CreateHandlerBase":367,"./component/tag/handlers/CreatePointHandler":368,"./component/tag/handlers/CreatePolygonHandler":369,"./component/tag/handlers/CreateRectDragHandler":370,"./component/tag/handlers/CreateRectHandler":371,"./component/tag/handlers/CreateVertexHandler":372,"./component/tag/handlers/EditVertexHandler":373,"./component/tag/handlers/TagHandlerBase":374,"./component/tag/tag/OutlineCreateTag":375,"./component/tag/tag/OutlineRenderTag":376,"./component/tag/tag/OutlineTag":377,"./component/tag/tag/RenderTag":378,"./component/tag/tag/SpotRenderTag":379,"./component/tag/tag/SpotTag":380,"./component/tag/tag/Tag":381,"./component/utils/HandlerBase":382,"./component/utils/MeshFactory":383,"./component/utils/MeshScene":384,"./component/zoom/ZoomComponent":385}],291:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var EdgeDirection_1 = require("./graph/edge/EdgeDirection"); exports.EdgeDirection = EdgeDirection_1.EdgeDirection; var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings"); @@ -18079,44 +22914,45 @@ exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculator var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator"); exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator; -},{"./graph/edge/EdgeCalculator":289,"./graph/edge/EdgeCalculatorCoefficients":290,"./graph/edge/EdgeCalculatorDirections":291,"./graph/edge/EdgeCalculatorSettings":292,"./graph/edge/EdgeDirection":293}],209:[function(require,module,exports){ +},{"./graph/edge/EdgeCalculator":405,"./graph/edge/EdgeCalculatorCoefficients":406,"./graph/edge/EdgeCalculatorDirections":407,"./graph/edge/EdgeCalculatorSettings":408,"./graph/edge/EdgeDirection":409}],292:[function(require,module,exports){ "use strict"; -var MapillaryError_1 = require("./error/MapillaryError"); -exports.MapillaryError = MapillaryError_1.MapillaryError; +Object.defineProperty(exports, "__esModule", { value: true }); +var AbortMapillaryError_1 = require("./error/AbortMapillaryError"); +exports.AbortMapillaryError = AbortMapillaryError_1.AbortMapillaryError; var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError"); exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError; var GraphMapillaryError_1 = require("./error/GraphMapillaryError"); exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError; -var MoveTypeMapillaryError_1 = require("./error/MoveTypeMapillaryError"); -exports.MoveTypeMapillaryError = MoveTypeMapillaryError_1.MoveTypeMapillaryError; -var NotImplementedMapillaryError_1 = require("./error/NotImplementedMapillaryError"); -exports.NotImplementedMapillaryError = NotImplementedMapillaryError_1.NotImplementedMapillaryError; -var ParameterMapillaryError_1 = require("./error/ParameterMapillaryError"); -exports.ParameterMapillaryError = ParameterMapillaryError_1.ParameterMapillaryError; -var InitializationMapillaryError_1 = require("./error/InitializationMapillaryError"); -exports.InitializationMapillaryError = InitializationMapillaryError_1.InitializationMapillaryError; +var MapillaryError_1 = require("./error/MapillaryError"); +exports.MapillaryError = MapillaryError_1.MapillaryError; -},{"./error/ArgumentMapillaryError":269,"./error/GraphMapillaryError":270,"./error/InitializationMapillaryError":271,"./error/MapillaryError":272,"./error/MoveTypeMapillaryError":273,"./error/NotImplementedMapillaryError":274,"./error/ParameterMapillaryError":275}],210:[function(require,module,exports){ +},{"./error/AbortMapillaryError":386,"./error/ArgumentMapillaryError":387,"./error/GraphMapillaryError":388,"./error/MapillaryError":389}],293:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Camera_1 = require("./geo/Camera"); exports.Camera = Camera_1.Camera; var GeoCoords_1 = require("./geo/GeoCoords"); exports.GeoCoords = GeoCoords_1.GeoCoords; +var ViewportCoords_1 = require("./geo/ViewportCoords"); +exports.ViewportCoords = ViewportCoords_1.ViewportCoords; var Spatial_1 = require("./geo/Spatial"); exports.Spatial = Spatial_1.Spatial; var Transform_1 = require("./geo/Transform"); exports.Transform = Transform_1.Transform; -},{"./geo/Camera":276,"./geo/GeoCoords":277,"./geo/Spatial":278,"./geo/Transform":279}],211:[function(require,module,exports){ +},{"./geo/Camera":390,"./geo/GeoCoords":391,"./geo/Spatial":392,"./geo/Transform":393,"./geo/ViewportCoords":394}],294:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var FilterCreator_1 = require("./graph/FilterCreator"); +exports.FilterCreator = FilterCreator_1.FilterCreator; var Graph_1 = require("./graph/Graph"); exports.Graph = Graph_1.Graph; var GraphCalculator_1 = require("./graph/GraphCalculator"); exports.GraphCalculator = GraphCalculator_1.GraphCalculator; +var GraphMode_1 = require("./graph/GraphMode"); +exports.GraphMode = GraphMode_1.GraphMode; var GraphService_1 = require("./graph/GraphService"); exports.GraphService = GraphService_1.GraphService; -var ImageLoader_1 = require("./graph/ImageLoader"); -exports.ImageLoader = ImageLoader_1.ImageLoader; var ImageLoadingService_1 = require("./graph/ImageLoadingService"); exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService; var MeshReader_1 = require("./graph/MeshReader"); @@ -18128,4537 +22964,8221 @@ exports.NodeCache = NodeCache_1.NodeCache; var Sequence_1 = require("./graph/Sequence"); exports.Sequence = Sequence_1.Sequence; -},{"./graph/Graph":280,"./graph/GraphCalculator":281,"./graph/GraphService":282,"./graph/ImageLoader":283,"./graph/ImageLoadingService":284,"./graph/MeshReader":285,"./graph/Node":286,"./graph/NodeCache":287,"./graph/Sequence":288}],212:[function(require,module,exports){ +},{"./graph/FilterCreator":395,"./graph/Graph":396,"./graph/GraphCalculator":397,"./graph/GraphMode":398,"./graph/GraphService":399,"./graph/ImageLoadingService":400,"./graph/MeshReader":401,"./graph/Node":402,"./graph/NodeCache":403,"./graph/Sequence":404}],295:[function(require,module,exports){ +"use strict"; +/** + * MapillaryJS is a WebGL JavaScript library for exploring street level imagery + * @name Mapillary + */ +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./Support")); +var Edge_1 = require("./Edge"); +exports.EdgeDirection = Edge_1.EdgeDirection; +var Error_1 = require("./Error"); +exports.AbortMapillaryError = Error_1.AbortMapillaryError; +var Render_1 = require("./Render"); +exports.RenderMode = Render_1.RenderMode; +var State_1 = require("./State"); +exports.TransitionMode = State_1.TransitionMode; +var Viewer_1 = require("./Viewer"); +exports.Alignment = Viewer_1.Alignment; +exports.ImageSize = Viewer_1.ImageSize; +exports.Viewer = Viewer_1.Viewer; +var Component_1 = require("./Component"); +exports.SliderMode = Component_1.SliderMode; +var TagComponent = require("./component/tag/Tag"); +exports.TagComponent = TagComponent; +var MarkerComponent = require("./component/marker/Marker"); +exports.MarkerComponent = MarkerComponent; +var PopupComponent = require("./component/popup/Popup"); +exports.PopupComponent = PopupComponent; + +},{"./Component":290,"./Edge":291,"./Error":292,"./Render":296,"./State":297,"./Support":298,"./Viewer":301,"./component/marker/Marker":330,"./component/popup/Popup":343,"./component/tag/Tag":353}],296:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var DOMRenderer_1 = require("./render/DOMRenderer"); +exports.DOMRenderer = DOMRenderer_1.DOMRenderer; +var GLRenderer_1 = require("./render/GLRenderer"); +exports.GLRenderer = GLRenderer_1.GLRenderer; +var GLRenderStage_1 = require("./render/GLRenderStage"); +exports.GLRenderStage = GLRenderStage_1.GLRenderStage; +var RenderCamera_1 = require("./render/RenderCamera"); +exports.RenderCamera = RenderCamera_1.RenderCamera; +var RenderMode_1 = require("./render/RenderMode"); +exports.RenderMode = RenderMode_1.RenderMode; +var RenderService_1 = require("./render/RenderService"); +exports.RenderService = RenderService_1.RenderService; + +},{"./render/DOMRenderer":410,"./render/GLRenderStage":411,"./render/GLRenderer":412,"./render/RenderCamera":413,"./render/RenderMode":414,"./render/RenderService":415}],297:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var RotationDelta_1 = require("./state/RotationDelta"); +exports.RotationDelta = RotationDelta_1.RotationDelta; +var State_1 = require("./state/State"); +exports.State = State_1.State; +var StateBase_1 = require("./state/states/StateBase"); +exports.StateBase = StateBase_1.StateBase; +var StateContext_1 = require("./state/StateContext"); +exports.StateContext = StateContext_1.StateContext; +var StateService_1 = require("./state/StateService"); +exports.StateService = StateService_1.StateService; +var TransitionMode_1 = require("./state/TransitionMode"); +exports.TransitionMode = TransitionMode_1.TransitionMode; +var InteractiveStateBase_1 = require("./state/states/InteractiveStateBase"); +exports.InteractiveStateBase = InteractiveStateBase_1.InteractiveStateBase; +var InteractiveWaitingState_1 = require("./state/states/InteractiveWaitingState"); +exports.InteractiveWaitingState = InteractiveWaitingState_1.InteractiveWaitingState; +var TraversingState_1 = require("./state/states/TraversingState"); +exports.TraversingState = TraversingState_1.TraversingState; +var WaitingState_1 = require("./state/states/WaitingState"); +exports.WaitingState = WaitingState_1.WaitingState; + +},{"./state/RotationDelta":416,"./state/State":417,"./state/StateContext":418,"./state/StateService":419,"./state/TransitionMode":420,"./state/states/InteractiveStateBase":421,"./state/states/InteractiveWaitingState":422,"./state/states/StateBase":423,"./state/states/TraversingState":424,"./state/states/WaitingState":425}],298:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var support = require("./utils/Support"); +/** + * Test whether the current browser supports the full + * functionality of MapillaryJS. + * + * @description The full functionality includes WebGL rendering. + * + * @return {boolean} + * + * @example `var supported = Mapillary.isSupported();` + */ +function isSupported() { + return isFallbackSupported() && + support.isWebGLSupportedCached(); +} +exports.isSupported = isSupported; +/** + * Test whether the current browser supports the fallback + * functionality of MapillaryJS. + * + * @description The fallback functionality does not include WebGL + * rendering, only 2D canvas rendering. + * + * @return {boolean} + * + * @example `var fallbackSupported = Mapillary.isFallbackSupported();` + */ +function isFallbackSupported() { + return support.isBrowser() && + support.isBlobSupported() && + support.isArraySupported() && + support.isFunctionSupported() && + support.isJSONSupported() && + support.isObjectSupported(); +} +exports.isFallbackSupported = isFallbackSupported; + +},{"./utils/Support":433}],299:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ImageTileLoader_1 = require("./tiles/ImageTileLoader"); +exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader; +var ImageTileStore_1 = require("./tiles/ImageTileStore"); +exports.ImageTileStore = ImageTileStore_1.ImageTileStore; +var TextureProvider_1 = require("./tiles/TextureProvider"); +exports.TextureProvider = TextureProvider_1.TextureProvider; +var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator"); +exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator; + +},{"./tiles/ImageTileLoader":426,"./tiles/ImageTileStore":427,"./tiles/RegionOfInterestCalculator":428,"./tiles/TextureProvider":429}],300:[function(require,module,exports){ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +var DOM_1 = require("./utils/DOM"); +exports.DOM = DOM_1.DOM; +var EventEmitter_1 = require("./utils/EventEmitter"); +exports.EventEmitter = EventEmitter_1.EventEmitter; +var Settings_1 = require("./utils/Settings"); +exports.Settings = Settings_1.Settings; +__export(require("./utils/Support")); +var Urls_1 = require("./utils/Urls"); +exports.Urls = Urls_1.Urls; + +},{"./utils/DOM":430,"./utils/EventEmitter":431,"./utils/Settings":432,"./utils/Support":433,"./utils/Urls":434}],301:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Alignment_1 = require("./viewer/Alignment"); +exports.Alignment = Alignment_1.Alignment; +var CacheService_1 = require("./viewer/CacheService"); +exports.CacheService = CacheService_1.CacheService; +var ComponentController_1 = require("./viewer/ComponentController"); +exports.ComponentController = ComponentController_1.ComponentController; +var Container_1 = require("./viewer/Container"); +exports.Container = Container_1.Container; +var Observer_1 = require("./viewer/Observer"); +exports.Observer = Observer_1.Observer; +var ImageSize_1 = require("./viewer/ImageSize"); +exports.ImageSize = ImageSize_1.ImageSize; +var KeyboardService_1 = require("./viewer/KeyboardService"); +exports.KeyboardService = KeyboardService_1.KeyboardService; +var LoadingService_1 = require("./viewer/LoadingService"); +exports.LoadingService = LoadingService_1.LoadingService; +var MouseService_1 = require("./viewer/MouseService"); +exports.MouseService = MouseService_1.MouseService; +var Navigator_1 = require("./viewer/Navigator"); +exports.Navigator = Navigator_1.Navigator; +var PlayService_1 = require("./viewer/PlayService"); +exports.PlayService = PlayService_1.PlayService; +var Projection_1 = require("./viewer/Projection"); +exports.Projection = Projection_1.Projection; +var SpriteService_1 = require("./viewer/SpriteService"); +exports.SpriteService = SpriteService_1.SpriteService; +var TouchService_1 = require("./viewer/TouchService"); +exports.TouchService = TouchService_1.TouchService; +var Viewer_1 = require("./viewer/Viewer"); +exports.Viewer = Viewer_1.Viewer; + +},{"./viewer/Alignment":435,"./viewer/CacheService":436,"./viewer/ComponentController":437,"./viewer/Container":438,"./viewer/ImageSize":439,"./viewer/KeyboardService":440,"./viewer/LoadingService":441,"./viewer/MouseService":442,"./viewer/Navigator":443,"./viewer/Observer":444,"./viewer/PlayService":445,"./viewer/Projection":446,"./viewer/SpriteService":447,"./viewer/TouchService":448,"./viewer/Viewer":449}],302:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var API_1 = require("../API"); +/** + * @class APIv3 + * + * @classdesc Provides methods for access of API v3. + */ +var APIv3 = /** @class */ (function () { + /** + * Create a new api v3 instance. + * + * @param {number} clientId - Client id for API requests. + * @param {number} [token] - Optional bearer token for API requests of + * protected resources. + * @param {ModelCreator} [creator] - Optional model creator instance. + */ + function APIv3(clientId, token, creator) { + this._clientId = clientId; + this._modelCreator = creator != null ? creator : new API_1.ModelCreator(); + this._model = this._modelCreator.createModel(clientId, token); + this._pageCount = 999; + this._pathImageByKey = "imageByKey"; + this._pathImageCloseTo = "imageCloseTo"; + this._pathImagesByH = "imagesByH"; + this._pathImageViewAdd = "imageViewAdd"; + this._pathSequenceByKey = "sequenceByKey"; + this._pathSequenceViewAdd = "sequenceViewAdd"; + this._propertiesCore = [ + "cl", + "l", + "sequence_key", + ]; + this._propertiesFill = [ + "captured_at", + "captured_with_camera_uuid", + "user", + "organization_key", + "private", + "project", + ]; + this._propertiesKey = [ + "key", + ]; + this._propertiesSequence = [ + "keys", + ]; + this._propertiesSpatial = [ + "atomic_scale", + "ca", + "calt", + "cca", + "cfocal", + "gpano", + "height", + "merge_cc", + "merge_version", + "c_rotation", + "orientation", + "width", + ]; + this._propertiesUser = [ + "username", + ]; + } + APIv3.prototype.imageByKeyFill$ = function (keys) { + return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ + this._pathImageByKey, + keys, + this._propertiesKey + .concat(this._propertiesFill) + .concat(this._propertiesSpatial), + this._propertiesKey + .concat(this._propertiesUser) + ])) + .map(function (value) { + if (!value) { + throw new Error("Images (" + keys.join(", ") + ") could not be found."); + } + return value.json.imageByKey; + }), this._pathImageByKey, keys); + }; + APIv3.prototype.imageByKeyFull$ = function (keys) { + return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ + this._pathImageByKey, + keys, + this._propertiesKey + .concat(this._propertiesCore) + .concat(this._propertiesFill) + .concat(this._propertiesSpatial), + this._propertiesKey + .concat(this._propertiesUser) + ])) + .map(function (value) { + if (!value) { + throw new Error("Images (" + keys.join(", ") + ") could not be found."); + } + return value.json.imageByKey; + }), this._pathImageByKey, keys); + }; + APIv3.prototype.imageCloseTo$ = function (lat, lon) { + var lonLat = lon + ":" + lat; + return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ + this._pathImageCloseTo, + [lonLat], + this._propertiesKey + .concat(this._propertiesCore) + .concat(this._propertiesFill) + .concat(this._propertiesSpatial), + this._propertiesKey + .concat(this._propertiesUser) + ])) + .map(function (value) { + return value != null ? value.json.imageCloseTo[lonLat] : null; + }), this._pathImageCloseTo, [lonLat]); + }; + APIv3.prototype.imagesByH$ = function (hs) { + var _this = this; + return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ + this._pathImagesByH, + hs, + { from: 0, to: this._pageCount }, + this._propertiesKey + .concat(this._propertiesCore) + ])) + .map(function (value) { + if (!value) { + value = { json: { imagesByH: {} } }; + for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) { + var h = hs_1[_i]; + value.json.imagesByH[h] = {}; + for (var i = 0; i <= _this._pageCount; i++) { + value.json.imagesByH[h][i] = null; + } + } + } + return value.json.imagesByH; + }), this._pathImagesByH, hs); + }; + APIv3.prototype.imageViewAdd$ = function (keys) { + return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys); + }; + APIv3.prototype.invalidateImageByKey = function (keys) { + this._invalidateGet(this._pathImageByKey, keys); + }; + APIv3.prototype.invalidateImagesByH = function (hs) { + this._invalidateGet(this._pathImagesByH, hs); + }; + APIv3.prototype.invalidateSequenceByKey = function (sKeys) { + this._invalidateGet(this._pathSequenceByKey, sKeys); + }; + APIv3.prototype.setToken = function (token) { + this._model.invalidate([]); + this._model = null; + this._model = this._modelCreator.createModel(this._clientId, token); + }; + APIv3.prototype.sequenceByKey$ = function (sequenceKeys) { + return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ + this._pathSequenceByKey, + sequenceKeys, + this._propertiesKey + .concat(this._propertiesSequence) + ])) + .map(function (value) { + if (!value) { + value = { json: { sequenceByKey: {} } }; + } + for (var _i = 0, sequenceKeys_1 = sequenceKeys; _i < sequenceKeys_1.length; _i++) { + var sequenceKey = sequenceKeys_1[_i]; + if (!(sequenceKey in value.json.sequenceByKey)) { + console.warn("Sequence data missing (" + sequenceKey + ")"); + value.json.sequenceByKey[sequenceKey] = { key: sequenceKey, keys: [] }; + } + } + return value.json.sequenceByKey; + }), this._pathSequenceByKey, sequenceKeys); + }; + APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) { + return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys); + }; + Object.defineProperty(APIv3.prototype, "clientId", { + get: function () { + return this._clientId; + }, + enumerable: true, + configurable: true + }); + APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) { + var _this = this; + return observable + .catch(function (error) { + _this._invalidateGet(path, paths); + throw error; + }); + }; + APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) { + var _this = this; + return observable + .catch(function (error) { + _this._invalidateCall(path, paths); + throw error; + }); + }; + APIv3.prototype._invalidateGet = function (path, paths) { + this._model.invalidate([path, paths]); + }; + APIv3.prototype._invalidateCall = function (path, paths) { + this._model.invalidate([path], [paths]); + }; + APIv3.prototype._wrapPromise$ = function (promise) { + return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); }); + }; + return APIv3; +}()); +exports.APIv3 = APIv3; +exports.default = APIv3; + +},{"../API":289,"rxjs/Observable":29}],303:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var falcor = require("falcor"); +var HttpDataSource = require("falcor-http-datasource"); +var Utils_1 = require("../Utils"); /** - * MapillaryJS is a WebGL JavaScript library for exploring street level imagery - * @name Mapillary + * @class ModelCreator + * + * @classdesc Creates API models. */ +var ModelCreator = /** @class */ (function () { + function ModelCreator() { + } + /** + * Creates a Falcor model. + * + * @description Max cache size will be set to 16 MB. Authorization + * header will be added if bearer token is supplied. + * + * @param {number} clientId - Client id for API requests. + * @param {number} [token] - Optional bearer token for API requests of + * protected resources. + * @returns {falcor.Model} Falcor model for HTTP requests. + */ + ModelCreator.prototype.createModel = function (clientId, token) { + var configuration = { + crossDomain: true, + withCredentials: false, + }; + if (token != null) { + configuration.headers = { "Authorization": "Bearer " + token }; + } + return new falcor.Model({ + maxSize: 16 * 1024 * 1024, + source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration), + }); + }; + return ModelCreator; +}()); +exports.ModelCreator = ModelCreator; +exports.default = ModelCreator; + +},{"../Utils":300,"falcor":15,"falcor-http-datasource":10}],304:[function(require,module,exports){ "use strict"; -var Edge_1 = require("./Edge"); -exports.EdgeDirection = Edge_1.EdgeDirection; -var Render_1 = require("./Render"); -exports.RenderMode = Render_1.RenderMode; -var Viewer_1 = require("./Viewer"); -exports.ImageSize = Viewer_1.ImageSize; -exports.Viewer = Viewer_1.Viewer; -var TagComponent = require("./component/tag/Tag"); -exports.TagComponent = TagComponent; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../Component"); +var Utils_1 = require("../Utils"); +var AttributionComponent = /** @class */ (function (_super) { + __extends(AttributionComponent, _super); + function AttributionComponent(name, container, navigator) { + return _super.call(this, name, container, navigator) || this; + } + AttributionComponent.prototype._activate = function () { + var _this = this; + this._disposable = Observable_1.Observable + .combineLatest(this._navigator.stateService.currentNode$, this._container.renderService.size$) + .map(function (_a) { + var node = _a[0], size = _a[1]; + return { + name: _this._name, + vnode: _this._getAttributionNode(node.username, node.key, node.capturedAt, size.width), + }; + }) + .subscribe(this._container.domRenderer.render$); + }; + AttributionComponent.prototype._deactivate = function () { + this._disposable.unsubscribe(); + }; + AttributionComponent.prototype._getDefaultConfiguration = function () { + return {}; + }; + AttributionComponent.prototype._getAttributionNode = function (username, key, capturedAt, width) { + var compact = width <= 640; + var mapillaryIcon = vd.h("div.AttributionMapillaryLogo", []); + var mapillaryLink = vd.h("a.AttributionIconContainer", { href: Utils_1.Urls.explore, target: "_blank" }, [mapillaryIcon]); + var imageBy = compact ? "" + username : "image by " + username; + var imageByContent = vd.h("div.AttributionUsername", { textContent: imageBy }, []); + var date = new Date(capturedAt).toDateString().split(" "); + var formatted = (date.length > 3 ? + compact ? + [date[3]] : + [date[1], date[2] + ",", date[3]] : + date).join(" "); + var dateContent = vd.h("div.AttributionDate", { textContent: formatted }, []); + var imageLink = vd.h("a.AttributionImageContainer", { href: Utils_1.Urls.exporeImage(key), target: "_blank" }, [imageByContent, dateContent]); + var compactClass = compact ? ".AttributionCompact" : ""; + return vd.h("div.AttributionContainer" + compactClass, {}, [mapillaryLink, imageLink]); + }; + AttributionComponent.componentName = "attribution"; + return AttributionComponent; +}(Component_1.Component)); +exports.AttributionComponent = AttributionComponent; +Component_1.ComponentService.register(AttributionComponent); +exports.default = AttributionComponent; -},{"./Edge":208,"./Render":213,"./Viewer":216,"./component/tag/Tag":248}],213:[function(require,module,exports){ +},{"../Component":290,"../Utils":300,"rxjs/Observable":29,"virtual-dom":246}],305:[function(require,module,exports){ "use strict"; -var DOMRenderer_1 = require("./render/DOMRenderer"); -exports.DOMRenderer = DOMRenderer_1.DOMRenderer; -var GLRenderer_1 = require("./render/GLRenderer"); -exports.GLRenderer = GLRenderer_1.GLRenderer; -var GLRenderStage_1 = require("./render/GLRenderStage"); -exports.GLRenderStage = GLRenderStage_1.GLRenderStage; -var RenderCamera_1 = require("./render/RenderCamera"); -exports.RenderCamera = RenderCamera_1.RenderCamera; -var RenderMode_1 = require("./render/RenderMode"); -exports.RenderMode = RenderMode_1.RenderMode; -var RenderService_1 = require("./render/RenderService"); -exports.RenderService = RenderService_1.RenderService; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Component_1 = require("../Component"); +var BackgroundComponent = /** @class */ (function (_super) { + __extends(BackgroundComponent, _super); + function BackgroundComponent(name, container, navigator) { + return _super.call(this, name, container, navigator) || this; + } + BackgroundComponent.prototype._activate = function () { + this._container.domRenderer.render$ + .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given image.") }); + }; + BackgroundComponent.prototype._deactivate = function () { + return; + }; + BackgroundComponent.prototype._getDefaultConfiguration = function () { + return {}; + }; + BackgroundComponent.prototype._getBackgroundNode = function (notice) { + // todo: add condition for when to display the DOM node + return vd.h("div.BackgroundWrapper", {}, [ + vd.h("p", { textContent: notice }, []), + ]); + }; + BackgroundComponent.componentName = "background"; + return BackgroundComponent; +}(Component_1.Component)); +exports.BackgroundComponent = BackgroundComponent; +Component_1.ComponentService.register(BackgroundComponent); +exports.default = BackgroundComponent; -},{"./render/DOMRenderer":294,"./render/GLRenderStage":295,"./render/GLRenderer":296,"./render/RenderCamera":297,"./render/RenderMode":298,"./render/RenderService":299}],214:[function(require,module,exports){ +},{"../Component":290,"virtual-dom":246}],306:[function(require,module,exports){ "use strict"; -var FrameGenerator_1 = require("./state/FrameGenerator"); -exports.FrameGenerator = FrameGenerator_1.FrameGenerator; -var StateService_1 = require("./state/StateService"); -exports.StateService = StateService_1.StateService; -var StateContext_1 = require("./state/StateContext"); -exports.StateContext = StateContext_1.StateContext; -var State_1 = require("./state/State"); -exports.State = State_1.State; -var StateBase_1 = require("./state/states/StateBase"); -exports.StateBase = StateBase_1.StateBase; -var TraversingState_1 = require("./state/states/TraversingState"); -exports.TraversingState = TraversingState_1.TraversingState; -var WaitingState_1 = require("./state/states/WaitingState"); -exports.WaitingState = WaitingState_1.WaitingState; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Component_1 = require("../Component"); +var Geo_1 = require("../Geo"); +var BearingComponent = /** @class */ (function (_super) { + __extends(BearingComponent, _super); + function BearingComponent(name, container, navigator) { + var _this = _super.call(this, name, container, navigator) || this; + _this._spatial = new Geo_1.Spatial(); + _this._svgNamespace = "http://www.w3.org/2000/svg"; + _this._distinctThreshold = Math.PI / 360; + return _this; + } + BearingComponent.prototype._activate = function () { + var _this = this; + var cameraBearingFov$ = this._container.renderService.renderCamera$ + .map(function (rc) { + var vFov = _this._spatial.degToRad(rc.perspective.fov); + var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ? + Math.PI : + Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2; + return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov]; + }) + .distinctUntilChanged(function (a1, a2) { + return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold && + Math.abs(a2[1] - a1[1]) < _this._distinctThreshold; + }); + this._renderSubscription = cameraBearingFov$ + .map(function (_a) { + var bearing = _a[0], fov = _a[1]; + var background = vd.h("div.BearingIndicatorBackground", {}, []); + var backgroundCircle = vd.h("div.BearingIndicatorBackgroundCircle", {}, []); + var north = _this._createNorth(bearing); + var cameraSector = _this._createCircleSectorCompass(_this._createCircleSector(Math.max(Math.PI / 20, fov), "#FFF")); + return { + name: _this._name, + vnode: vd.h("div.BearingIndicatorContainer", { oncontextmenu: function (event) { event.preventDefault(); } }, [ + background, + backgroundCircle, + north, + cameraSector, + ]), + }; + }) + .subscribe(this._container.domRenderer.render$); + }; + BearingComponent.prototype._deactivate = function () { + this._renderSubscription.unsubscribe(); + }; + BearingComponent.prototype._getDefaultConfiguration = function () { + return {}; + }; + BearingComponent.prototype._createCircleSectorCompass = function (cameraSector) { + var group = vd.h("g", { + attributes: { transform: "translate(1,1)" }, + namespace: this._svgNamespace, + }, [cameraSector]); + var svg = vd.h("svg", { + attributes: { viewBox: "0 0 2 2" }, + namespace: this._svgNamespace, + style: { + height: "30px", + left: "4px", + position: "absolute", + top: "4px", + width: "30px", + }, + }, [group]); + return svg; + }; + BearingComponent.prototype._createCircleSector = function (fov, fill) { + if (fov > 2 * Math.PI - Math.PI / 90) { + return vd.h("circle", { + attributes: { cx: "0", cy: "0", fill: fill, r: "1" }, + namespace: this._svgNamespace, + }, []); + } + var arcStart = -Math.PI / 2 - fov / 2; + var arcEnd = arcStart + fov; + var startX = Math.cos(arcStart); + var startY = Math.sin(arcStart); + var endX = Math.cos(arcEnd); + var endY = Math.sin(arcEnd); + var largeArc = fov >= Math.PI ? 1 : 0; + var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY; + return vd.h("path", { + attributes: { d: description, fill: fill }, + namespace: this._svgNamespace, + }, []); + }; + BearingComponent.prototype._createNorth = function (bearing) { + var north = vd.h("div.BearingNorth", []); + var container = vd.h("div.BearingNorthContainer", { style: { transform: "rotateZ(" + -bearing * 180 / Math.PI + "deg)" } }, [north]); + return container; + }; + BearingComponent.componentName = "bearing"; + return BearingComponent; +}(Component_1.Component)); +exports.BearingComponent = BearingComponent; +Component_1.ComponentService.register(BearingComponent); +exports.default = BearingComponent; + +},{"../Component":290,"../Geo":293,"virtual-dom":246}],307:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Edge_1 = require("../Edge"); +var Component_1 = require("../Component"); +var CacheComponent = /** @class */ (function (_super) { + __extends(CacheComponent, _super); + function CacheComponent(name, container, navigator) { + return _super.call(this, name, container, navigator) || this; + } + /** + * Set the cache depth. + * + * Configures the cache depth. The cache depth can be different for + * different edge direction types. + * + * @param {ICacheDepth} depth - Cache depth structure. + */ + CacheComponent.prototype.setDepth = function (depth) { + this.configure({ depth: depth }); + }; + CacheComponent.prototype._activate = function () { + var _this = this; + this._sequenceSubscription = Observable_1.Observable + .combineLatest(this._navigator.stateService.currentNode$ + .switchMap(function (node) { + return node.sequenceEdges$; + }) + .filter(function (status) { + return status.cached; + }), this._configuration$) + .switchMap(function (nc) { + var status = nc[0]; + var configuration = nc[1]; + var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence)); + var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth); + var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth); + return Observable_1.Observable + .merge(next$, prev$) + .catch(function (error, caught) { + console.error("Failed to cache sequence edges.", error); + return Observable_1.Observable.empty(); + }); + }) + .subscribe(function () { }); + this._spatialSubscription = this._navigator.stateService.currentNode$ + .switchMap(function (node) { + return Observable_1.Observable + .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$ + .filter(function (status) { + return status.cached; + })); + }) + .combineLatest(this._configuration$, function (ns, configuration) { + return [ns[0], ns[1], configuration]; + }) + .switchMap(function (args) { + var node = args[0]; + var edges = args[1].edges; + var depth = args[2].depth; + var panoDepth = Math.max(0, Math.min(2, depth.pano)); + var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step)); + var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn)); + var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth); + var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth); + var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth); + var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth); + var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth); + var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth); + var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth); + var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth); + return Observable_1.Observable + .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$) + .catch(function (error, caught) { + console.error("Failed to cache spatial edges.", error); + return Observable_1.Observable.empty(); + }); + }) + .subscribe(function () { }); + }; + CacheComponent.prototype._deactivate = function () { + this._sequenceSubscription.unsubscribe(); + this._spatialSubscription.unsubscribe(); + }; + CacheComponent.prototype._getDefaultConfiguration = function () { + return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } }; + }; + CacheComponent.prototype._cache$ = function (edges, direction, depth) { + var _this = this; + return Observable_1.Observable + .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth)) + .expand(function (ed) { + var es = ed[0]; + var d = ed[1]; + var edgesDepths$ = []; + if (d > 0) { + for (var _i = 0, es_1 = es; _i < es_1.length; _i++) { + var edge = es_1[_i]; + if (edge.data.direction === direction) { + edgesDepths$.push(Observable_1.Observable + .zip(_this._navigator.graphService.cacheNode$(edge.to) + .mergeMap(function (n) { + return _this._nodeToEdges$(n, direction); + }), Observable_1.Observable.of(d - 1))); + } + } + } + return Observable_1.Observable + .from(edgesDepths$) + .mergeAll(); + }) + .skip(1); + }; + CacheComponent.prototype._nodeToEdges$ = function (node, direction) { + return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ? + node.sequenceEdges$ : + node.spatialEdges$) + .first(function (status) { + return status.cached; + }) + .map(function (status) { + return status.edges; + }); + }; + CacheComponent.componentName = "cache"; + return CacheComponent; +}(Component_1.Component)); +exports.CacheComponent = CacheComponent; +Component_1.ComponentService.register(CacheComponent); +exports.default = CacheComponent; -},{"./state/FrameGenerator":300,"./state/State":301,"./state/StateContext":302,"./state/StateService":303,"./state/states/StateBase":304,"./state/states/TraversingState":305,"./state/states/WaitingState":306}],215:[function(require,module,exports){ +},{"../Component":290,"../Edge":291,"rxjs/Observable":29}],308:[function(require,module,exports){ "use strict"; -var EventEmitter_1 = require("./utils/EventEmitter"); -exports.EventEmitter = EventEmitter_1.EventEmitter; -var Settings_1 = require("./utils/Settings"); -exports.Settings = Settings_1.Settings; -var Urls_1 = require("./utils/Urls"); -exports.Urls = Urls_1.Urls; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); +var Subject_1 = require("rxjs/Subject"); +var Utils_1 = require("../Utils"); +var Component = /** @class */ (function (_super) { + __extends(Component, _super); + function Component(name, container, navigator) { + var _this = _super.call(this) || this; + _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false); + _this._configurationSubject$ = new Subject_1.Subject(); + _this._activated = false; + _this._container = container; + _this._name = name; + _this._navigator = navigator; + _this._configuration$ = + _this._configurationSubject$ + .startWith(_this.defaultConfiguration) + .scan(function (conf, newConf) { + for (var key in newConf) { + if (newConf.hasOwnProperty(key)) { + conf[key] = newConf[key]; + } + } + return conf; + }) + .publishReplay(1) + .refCount(); + _this._configuration$.subscribe(function () { }); + return _this; + } + Object.defineProperty(Component.prototype, "activated", { + get: function () { + return this._activated; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Component.prototype, "activated$", { + get: function () { + return this._activated$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Component.prototype, "defaultConfiguration", { + /** + * Get default configuration. + * + * @returns {TConfiguration} Default configuration for component. + */ + get: function () { + return this._getDefaultConfiguration(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Component.prototype, "configuration$", { + get: function () { + return this._configuration$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Component.prototype, "name", { + get: function () { + return this._name; + }, + enumerable: true, + configurable: true + }); + Component.prototype.activate = function (conf) { + if (this._activated) { + return; + } + if (conf !== undefined) { + this._configurationSubject$.next(conf); + } + this._activated = true; + this._activate(); + this._activated$.next(true); + }; + Component.prototype.configure = function (conf) { + this._configurationSubject$.next(conf); + }; + Component.prototype.deactivate = function () { + if (!this._activated) { + return; + } + this._activated = false; + this._deactivate(); + this._container.domRenderer.clear(this._name); + this._container.glRenderer.clear(this._name); + this._activated$.next(false); + }; + /** + * Detect the viewer's new width and height and resize the component's + * rendered elements accordingly if applicable. + */ + Component.prototype.resize = function () { return; }; + /** + * Component name. Used when interacting with component through the Viewer's API. + */ + Component.componentName = "not_worthy"; + return Component; +}(Utils_1.EventEmitter)); +exports.Component = Component; +exports.default = Component; -},{"./utils/EventEmitter":307,"./utils/Settings":308,"./utils/Urls":309}],216:[function(require,module,exports){ +},{"../Utils":300,"rxjs/BehaviorSubject":26,"rxjs/Subject":34}],309:[function(require,module,exports){ "use strict"; -var Container_1 = require("./viewer/Container"); -exports.Container = Container_1.Container; -var EventLauncher_1 = require("./viewer/EventLauncher"); -exports.EventLauncher = EventLauncher_1.EventLauncher; -var ImageSize_1 = require("./viewer/ImageSize"); -exports.ImageSize = ImageSize_1.ImageSize; -var LoadingService_1 = require("./viewer/LoadingService"); -exports.LoadingService = LoadingService_1.LoadingService; -var MouseService_1 = require("./viewer/MouseService"); -exports.MouseService = MouseService_1.MouseService; -var Navigator_1 = require("./viewer/Navigator"); -exports.Navigator = Navigator_1.Navigator; -var ComponentController_1 = require("./viewer/ComponentController"); -exports.ComponentController = ComponentController_1.ComponentController; -var SpriteAlignment_1 = require("./viewer/SpriteAlignment"); -exports.SpriteAlignment = SpriteAlignment_1.SpriteAlignment; -var SpriteService_1 = require("./viewer/SpriteService"); -exports.SpriteService = SpriteService_1.SpriteService; -var TouchService_1 = require("./viewer/TouchService"); -exports.TouchService = TouchService_1.TouchService; -exports.TouchMove = TouchService_1.TouchMove; -var Viewer_1 = require("./viewer/Viewer"); -exports.Viewer = Viewer_1.Viewer; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var _ = require("underscore"); +var Error_1 = require("../Error"); +var ComponentService = /** @class */ (function () { + function ComponentService(container, navigator) { + this._components = {}; + for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) { + var component = _a[_i]; + this._components[component.componentName] = { + active: false, + component: new component(component.componentName, container, navigator), + }; + } + this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator); + this._coverComponent.activate(); + this._coverActivated = true; + } + ComponentService.register = function (component) { + if (ComponentService.registeredComponents[component.componentName] === undefined) { + ComponentService.registeredComponents[component.componentName] = component; + } + }; + ComponentService.registerCover = function (coverComponent) { + ComponentService.registeredCoverComponent = coverComponent; + }; + Object.defineProperty(ComponentService.prototype, "coverActivated", { + get: function () { + return this._coverActivated; + }, + enumerable: true, + configurable: true + }); + ComponentService.prototype.activateCover = function () { + if (this._coverActivated) { + return; + } + this._coverActivated = true; + for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) { + var component = _a[_i]; + if (component.active) { + component.component.deactivate(); + } + } + return; + }; + ComponentService.prototype.deactivateCover = function () { + if (!this._coverActivated) { + return; + } + this._coverActivated = false; + for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) { + var component = _a[_i]; + if (component.active) { + component.component.activate(); + } + } + return; + }; + ComponentService.prototype.activate = function (name) { + this._checkName(name); + this._components[name].active = true; + if (!this._coverActivated) { + this.get(name).activate(); + } + }; + ComponentService.prototype.configure = function (name, conf) { + this._checkName(name); + this.get(name).configure(conf); + }; + ComponentService.prototype.deactivate = function (name) { + this._checkName(name); + this._components[name].active = false; + if (!this._coverActivated) { + this.get(name).deactivate(); + } + }; + ComponentService.prototype.resize = function () { + for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) { + var component = _a[_i]; + component.component.resize(); + } + }; + ComponentService.prototype.get = function (name) { + return this._components[name].component; + }; + ComponentService.prototype.getCover = function () { + return this._coverComponent; + }; + ComponentService.prototype._checkName = function (name) { + if (!(name in this._components)) { + throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name); + } + }; + ComponentService.registeredComponents = {}; + return ComponentService; +}()); +exports.ComponentService = ComponentService; +exports.default = ComponentService; + +},{"../Error":292,"underscore":242}],310:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../Component"); +var Utils_1 = require("../Utils"); +var Viewer_1 = require("../Viewer"); +var CoverComponent = /** @class */ (function (_super) { + __extends(CoverComponent, _super); + function CoverComponent(name, container, navigator) { + return _super.call(this, name, container, navigator) || this; + } + CoverComponent.prototype._activate = function () { + var _this = this; + this._configuration$ + .distinctUntilChanged(undefined, function (configuration) { + return configuration.state; + }) + .switchMap(function (configuration) { + return Observable_1.Observable + .combineLatest(Observable_1.Observable.of(configuration.state), _this._navigator.stateService.currentNode$); + }) + .switchMap(function (_a) { + var state = _a[0], node = _a[1]; + var keySrc$ = Observable_1.Observable + .combineLatest(Observable_1.Observable.of(node.key), node.image$ + .map(function (image) { + return image.src; + })); + return state === Component_1.CoverState.Visible ? keySrc$.first() : keySrc$; + }) + .distinctUntilChanged(function (_a, _b) { + var k1 = _a[0], s1 = _a[1]; + var k2 = _b[0], s2 = _b[1]; + return k1 === k2 && s1 === s2; + }) + .map(function (_a) { + var key = _a[0], src = _a[1]; + return { key: key, src: src }; + }) + .subscribe(this._configurationSubject$); + this._renderSubscription = Observable_1.Observable + .combineLatest(this._configuration$, this._container.renderService.size$) + .map(function (_a) { + var configuration = _a[0], size = _a[1]; + if (!configuration.key) { + return { name: _this._name, vnode: vd.h("div", []) }; + } + var compactClass = size.width <= 640 || size.height <= 480 ? ".CoverCompact" : ""; + if (configuration.state === Component_1.CoverState.Hidden) { + var doneContainer = vd.h("div.CoverContainer.CoverDone" + compactClass, [_this._getCoverBackgroundVNode(configuration)]); + return { name: _this._name, vnode: doneContainer }; + } + var container = vd.h("div.CoverContainer" + compactClass, [_this._getCoverButtonVNode(configuration)]); + return { name: _this._name, vnode: container }; + }) + .subscribe(this._container.domRenderer.render$); + }; + CoverComponent.prototype._deactivate = function () { + this._renderSubscription.unsubscribe(); + this._keySubscription.unsubscribe(); + }; + CoverComponent.prototype._getDefaultConfiguration = function () { + return { state: Component_1.CoverState.Visible }; + }; + CoverComponent.prototype._getCoverButtonVNode = function (configuration) { + var _this = this; + var cover = configuration.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover"; + var coverButton = vd.h("div.CoverButton", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, [vd.h("div.CoverButtonIcon", [])]); + var coverLogo = vd.h("a.CoverLogo", { href: Utils_1.Urls.explore, target: "_blank" }, []); + return vd.h(cover, [this._getCoverBackgroundVNode(configuration), coverButton, coverLogo]); + }; + CoverComponent.prototype._getCoverBackgroundVNode = function (conf) { + var url = conf.src != null ? + conf.src : Utils_1.Urls.thumbnail(conf.key, Viewer_1.ImageSize.Size640); + var properties = { style: { backgroundImage: "url(" + url + ")" } }; + var children = []; + if (conf.state === Component_1.CoverState.Loading) { + children.push(vd.h("div.Spinner", {}, [])); + } + return vd.h("div.CoverBackground", properties, children); + }; + CoverComponent.componentName = "cover"; + return CoverComponent; +}(Component_1.Component)); +exports.CoverComponent = CoverComponent; +Component_1.ComponentService.registerCover(CoverComponent); +exports.default = CoverComponent; -},{"./viewer/ComponentController":310,"./viewer/Container":311,"./viewer/EventLauncher":312,"./viewer/ImageSize":313,"./viewer/LoadingService":314,"./viewer/MouseService":315,"./viewer/Navigator":316,"./viewer/SpriteAlignment":317,"./viewer/SpriteService":318,"./viewer/TouchService":319,"./viewer/Viewer":320}],217:[function(require,module,exports){ +},{"../Component":290,"../Utils":300,"../Viewer":301,"rxjs/Observable":29,"virtual-dom":246}],311:[function(require,module,exports){ +"use strict"; /// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var _ = require("underscore"); +var vd = require("virtual-dom"); +var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); +var Component_1 = require("../Component"); +var DebugComponent = /** @class */ (function (_super) { + __extends(DebugComponent, _super); + function DebugComponent() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this._open$ = new BehaviorSubject_1.BehaviorSubject(false); + return _this; + } + DebugComponent.prototype._activate = function () { + var _this = this; + this._disposable = this._navigator.stateService.currentState$ + .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) { + return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) }; + }) + .subscribe(this._container.domRenderer.render$); + }; + DebugComponent.prototype._deactivate = function () { + this._disposable.unsubscribe(); + }; + DebugComponent.prototype._getDefaultConfiguration = function () { + return {}; + }; + DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) { + var ret = []; + ret.push(vd.h("h2", "Node")); + if (frame.state.currentNode) { + ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key)); + } + if (frame.state.previousNode) { + ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key)); + } + ret.push(vd.h("h2", "Loading")); + var total = 0; + var loaded = 0; + var loading = 0; + for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) { + var loadStat = _a[_i]; + total += loadStat.loaded; + if (loadStat.loaded !== loadStat.total) { + loading++; + } + else { + loaded++; + } + } + ret.push(vd.h("p", "Loaded Images: " + loaded)); + ret.push(vd.h("p", "Loading Images: " + loading)); + ret.push(vd.h("p", "Total bytes loaded: " + total)); + ret.push(vd.h("h2", "Camera")); + ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x)); + ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y)); + ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z)); + ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x)); + ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y)); + ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z)); + ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x)); + ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y)); + ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z)); + return ret; + }; + DebugComponent.prototype._getDebugVNode = function (open, info) { + if (open) { + return vd.h("div.Debug", {}, [ + vd.h("h2", {}, ["Debug"]), + this._getDebugVNodeButton(open), + vd.h("pre", {}, info), + ]); + } + else { + return this._getDebugVNodeButton(open); + } + }; + DebugComponent.prototype._getDebugVNodeButton = function (open) { + var buttonText = open ? "Disable Debug" : "D"; + var buttonCssClass = open ? "" : ".DebugButtonFixed"; + if (open) { + return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]); + } + else { + return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]); + } + }; + DebugComponent.prototype._closeDebugElement = function (open) { + this._open$.next(false); + }; + DebugComponent.prototype._openDebugElement = function () { + this._open$.next(true); + }; + DebugComponent.componentName = "debug"; + return DebugComponent; +}(Component_1.Component)); +exports.DebugComponent = DebugComponent; +Component_1.ComponentService.register(DebugComponent); +exports.default = DebugComponent; + +},{"../Component":290,"rxjs/BehaviorSubject":26,"underscore":242,"virtual-dom":246}],312:[function(require,module,exports){ "use strict"; -var falcor = require("falcor"); -var HttpDataSource = require("falcor-http-datasource"); +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/observable/defer"); -require("rxjs/add/observable/fromPromise"); -require("rxjs/add/operator/catch"); -require("rxjs/add/operator/map"); +var Component_1 = require("../Component"); var Utils_1 = require("../Utils"); -var APIv3 = (function () { - function APIv3(clientId, model) { - this._clientId = clientId; - this._model = model != null ? - model : - new falcor.Model({ - source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), { - crossDomain: true, - withCredentials: false, - }), - }); - this._pageCount = 999; - this._pathImageByKey = "imageByKey"; - this._pathImageCloseTo = "imageCloseTo"; - this._pathImagesByH = "imagesByH"; - this._pathImageViewAdd = "imageViewAdd"; - this._pathSequenceByKey = "sequenceByKey"; - this._pathSequenceViewAdd = "sequenceViewAdd"; - this._propertiesCore = [ - "cl", - "l", - "sequence", - ]; - this._propertiesFill = [ - "captured_at", - "user", - ]; - this._propertiesKey = [ - "key", - ]; - this._propertiesSequence = [ - "keys", - ]; - this._propertiesSpatial = [ - "atomic_scale", - "ca", - "calt", - "cca", - "cfocal", - "gpano", - "height", - "merge_cc", - "merge_version", - "c_rotation", - "orientation", - "width", - ]; - this._propertiesUser = [ - "username", - ]; +var ImageComponent = /** @class */ (function (_super) { + __extends(ImageComponent, _super); + function ImageComponent(name, container, navigator, dom) { + var _this = _super.call(this, name, container, navigator) || this; + _this._canvasId = container.id + "-" + _this._name; + _this._dom = !!dom ? dom : new Utils_1.DOM(); + return _this; } - ; - APIv3.prototype.imageByKeyFill$ = function (keys) { - return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ - this._pathImageByKey, - keys, - this._propertiesKey.concat(this._propertiesFill).concat(this._propertiesSpatial), - this._propertiesKey.concat(this._propertiesUser)])) - .map(function (value) { - return value.json.imageByKey; - }), this._pathImageByKey, keys); + ImageComponent.prototype._activate = function () { + var _this = this; + var canvasSize$ = this._container.domRenderer.element$ + .map(function (element) { + return _this._dom.document.getElementById(_this._canvasId); + }) + .filter(function (canvas) { + return !!canvas; + }) + .map(function (canvas) { + var adaptableDomRenderer = canvas.parentElement; + var width = adaptableDomRenderer.offsetWidth; + var height = adaptableDomRenderer.offsetHeight; + return [canvas, { height: height, width: width }]; + }) + .distinctUntilChanged(function (s1, s2) { + return s1.height === s2.height && s1.width === s2.width; + }, function (_a) { + var canvas = _a[0], size = _a[1]; + return size; + }); + this.drawSubscription = Observable_1.Observable + .combineLatest(canvasSize$, this._navigator.stateService.currentNode$) + .subscribe(function (_a) { + var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1]; + canvas.width = size.width; + canvas.height = size.height; + canvas + .getContext("2d") + .drawImage(node.image, 0, 0, size.width, size.height); + }); + this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) }); }; - APIv3.prototype.imageByKeyFull$ = function (keys) { - return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ - this._pathImageByKey, - keys, - this._propertiesKey.concat(this._propertiesCore).concat(this._propertiesFill).concat(this._propertiesSpatial), - this._propertiesKey.concat(this._propertiesUser)])) - .map(function (value) { - return value.json.imageByKey; - }), this._pathImageByKey, keys); + ImageComponent.prototype._deactivate = function () { + this.drawSubscription.unsubscribe(); }; - APIv3.prototype.imageCloseTo$ = function (lat, lon) { - var lonLat = lon + ":" + lat; - return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ - this._pathImageCloseTo, - [lonLat], - this._propertiesKey.concat(this._propertiesCore).concat(this._propertiesFill).concat(this._propertiesSpatial), - this._propertiesKey.concat(this._propertiesUser)])) - .map(function (value) { - return value != null ? value.json.imageCloseTo[lonLat] : null; - }), this._pathImageCloseTo, [lonLat]); + ImageComponent.prototype._getDefaultConfiguration = function () { + return {}; }; - APIv3.prototype.imagesByH$ = function (hs) { + ImageComponent.componentName = "image"; + return ImageComponent; +}(Component_1.Component)); +exports.ImageComponent = ImageComponent; +Component_1.ComponentService.register(ImageComponent); +exports.default = ImageComponent; + +},{"../Component":290,"../Utils":300,"rxjs/Observable":29,"virtual-dom":246}],313:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var _ = require("underscore"); +var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../Component"); +var LoadingComponent = /** @class */ (function (_super) { + __extends(LoadingComponent, _super); + function LoadingComponent(name, container, navigator) { + return _super.call(this, name, container, navigator) || this; + } + LoadingComponent.prototype._activate = function () { var _this = this; - return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ - this._pathImagesByH, - hs, - { from: 0, to: this._pageCount }, - this._propertiesKey.concat(this._propertiesCore), - this._propertiesKey])) - .map(function (value) { - if (value == null) { - value = { json: { imagesByH: {} } }; - for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) { - var h = hs_1[_i]; - value.json.imagesByH[h] = {}; - for (var i = 0; i <= _this._pageCount; i++) { - value.json.imagesByH[h][i] = null; - } + this._loadingSubscription = this._navigator.loadingService.loading$ + .switchMap(function (loading) { + return loading ? + _this._navigator.imageLoadingService.loadstatus$ : + Observable_1.Observable.of({}); + }) + .map(function (loadStatus) { + var total = 0; + var loaded = 0; + for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) { + var loadStat = _a[_i]; + if (loadStat.loaded !== loadStat.total) { + loaded += loadStat.loaded; + total += loadStat.total; } - } - return value.json.imagesByH; - }), this._pathImagesByH, hs); - }; - APIv3.prototype.imageViewAdd$ = function (keys) { - return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys); - }; - APIv3.prototype.invalidateImageByKey = function (keys) { - this._invalidateGet(this._pathImageByKey, keys); + } + var percentage = 100; + if (total !== 0) { + percentage = (loaded / total) * 100; + } + return { name: _this._name, vnode: _this._getBarVNode(percentage) }; + }) + .subscribe(this._container.domRenderer.render$); }; - APIv3.prototype.invalidateImagesByH = function (hs) { - this._invalidateGet(this._pathImagesByH, hs); + LoadingComponent.prototype._deactivate = function () { + this._loadingSubscription.unsubscribe(); }; - APIv3.prototype.invalidateSequenceByKey = function (sKeys) { - this._invalidateGet(this._pathSequenceByKey, sKeys); + LoadingComponent.prototype._getDefaultConfiguration = function () { + return {}; }; - APIv3.prototype.sequenceByKey$ = function (sequenceKeys) { - return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([ - this._pathSequenceByKey, - sequenceKeys, - this._propertiesKey.concat(this._propertiesSequence)])) - .map(function (value) { - return value.json.sequenceByKey; - }), this._pathSequenceByKey, sequenceKeys); + LoadingComponent.prototype._getBarVNode = function (percentage) { + var loadingBarStyle = {}; + var loadingContainerStyle = {}; + if (percentage !== 100) { + loadingBarStyle.width = percentage.toFixed(0) + "%"; + loadingBarStyle.opacity = "1"; + } + else { + loadingBarStyle.width = "100%"; + loadingBarStyle.opacity = "0"; + } + return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]); }; - APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) { - return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys); + LoadingComponent.componentName = "loading"; + return LoadingComponent; +}(Component_1.Component)); +exports.LoadingComponent = LoadingComponent; +Component_1.ComponentService.register(LoadingComponent); +exports.default = LoadingComponent; + +},{"../Component":290,"rxjs/Observable":29,"underscore":242,"virtual-dom":246}],314:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - Object.defineProperty(APIv3.prototype, "clientId", { - get: function () { - return this._clientId; - }, - enumerable: true, - configurable: true - }); - APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) { +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); +var Edge_1 = require("../Edge"); +var Error_1 = require("../Error"); +var Component_1 = require("../Component"); +/** + * @class NavigationComponent + * + * @classdesc Fallback navigation component for environments without WebGL support. + * + * Replaces the functionality in the Direction and Sequence components. + */ +var NavigationComponent = /** @class */ (function (_super) { + __extends(NavigationComponent, _super); + function NavigationComponent(name, container, navigator) { + var _this = _super.call(this, name, container, navigator) || this; + _this._seqNames = {}; + _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev"; + _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next"; + _this._spaTopNames = {}; + _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft"; + _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left"; + _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward"; + _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right"; + _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright"; + _this._spaBottomNames = {}; + _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround"; + _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward"; + return _this; + } + NavigationComponent.prototype._activate = function () { var _this = this; - return observable - .catch(function (error) { - _this._invalidateGet(path, paths); - throw error; - }); + this._renderSubscription = Observable_1.Observable + .combineLatest(this._navigator.stateService.currentNode$, this._configuration$) + .switchMap(function (_a) { + var node = _a[0], configuration = _a[1]; + var sequenceEdges$ = configuration.sequence ? + node.sequenceEdges$ + .map(function (status) { + return status.edges + .map(function (edge) { + return edge.data.direction; + }); + }) : + Observable_1.Observable.of([]); + var spatialEdges$ = !node.pano && configuration.spatial ? + node.spatialEdges$ + .map(function (status) { + return status.edges + .map(function (edge) { + return edge.data.direction; + }); + }) : + Observable_1.Observable.of([]); + return Observable_1.Observable + .combineLatest(sequenceEdges$, spatialEdges$) + .map(function (_a) { + var seq = _a[0], spa = _a[1]; + return seq.concat(spa); + }); + }) + .map(function (edgeDirections) { + var seqs = _this._createArrowRow(_this._seqNames, edgeDirections); + var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections); + var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections); + var seqContainer = vd.h("div.NavigationSequence", seqs); + var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops); + var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms); + var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]); + return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) }; + }) + .subscribe(this._container.domRenderer.render$); }; - APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) { - var _this = this; - return observable - .catch(function (error) { - _this._invalidateCall(path, paths); - throw error; - }); + NavigationComponent.prototype._deactivate = function () { + this._renderSubscription.unsubscribe(); }; - APIv3.prototype._invalidateGet = function (path, paths) { - this._model.invalidate([path, paths]); + NavigationComponent.prototype._getDefaultConfiguration = function () { + return { sequence: true, spatial: true }; }; - APIv3.prototype._invalidateCall = function (path, paths) { - this._model.invalidate([path], [paths]); + NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) { + var arrows = []; + for (var arrowName in arrowNames) { + if (!(arrowNames.hasOwnProperty(arrowName))) { + continue; + } + var direction = Edge_1.EdgeDirection[arrowName]; + if (edgeDirections.indexOf(direction) !== -1) { + arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible")); + } + else { + arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden")); + } + } + return arrows; }; - APIv3.prototype._wrapPromise$ = function (promise) { - return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); }); + NavigationComponent.prototype._createVNode = function (direction, name, visibility) { + var _this = this; + return vd.h("span.Direction.Direction" + name, { + onclick: function (ev) { + _this._navigator.moveDir$(direction) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); + } + }); + }, + style: { + visibility: visibility, + }, + }, []); }; - return APIv3; -}()); -exports.APIv3 = APIv3; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = APIv3; + NavigationComponent.componentName = "navigation"; + return NavigationComponent; +}(Component_1.Component)); +exports.NavigationComponent = NavigationComponent; +Component_1.ComponentService.register(NavigationComponent); +exports.default = NavigationComponent; -},{"../Utils":215,"falcor":13,"falcor-http-datasource":8,"rxjs/Observable":28,"rxjs/add/observable/defer":38,"rxjs/add/observable/fromPromise":42,"rxjs/add/operator/catch":48,"rxjs/add/operator/map":60}],218:[function(require,module,exports){ -/// +},{"../Component":290,"../Edge":291,"../Error":292,"rxjs/Observable":29,"virtual-dom":246}],315:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var _ = require("underscore"); var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); var Component_1 = require("../Component"); -var AttributionComponent = (function (_super) { - __extends(AttributionComponent, _super); - function AttributionComponent(name, container, navigator) { - _super.call(this, name, container, navigator); +var DescriptionState = /** @class */ (function () { + function DescriptionState() { } - AttributionComponent.prototype._activate = function () { + return DescriptionState; +}()); +var RouteState = /** @class */ (function () { + function RouteState() { + } + return RouteState; +}()); +var RouteTrack = /** @class */ (function () { + function RouteTrack() { + this.nodeInstructions = []; + this.nodeInstructionsOrdered = []; + } + return RouteTrack; +}()); +var RouteComponent = /** @class */ (function (_super) { + __extends(RouteComponent, _super); + function RouteComponent(name, container, navigator) { + return _super.call(this, name, container, navigator) || this; + } + RouteComponent.prototype._activate = function () { var _this = this; - this._disposable = this._navigator.stateService.currentNode$ - .map(function (node) { - return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) }; - }) - .subscribe(this._container.domRenderer.render$); + var _slowedStream$; + _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) { + return (frame.id % 2) === 0; + }).filter(function (frame) { + return frame.state.nodesAhead < 15; + }).distinctUntilChanged(undefined, function (frame) { + return frame.state.lastNode.key; + }); + var _routeTrack$; + _routeTrack$ = this.configuration$.mergeMap(function (conf) { + return Observable_1.Observable.from(conf.paths); + }).distinct(function (p) { + return p.sequenceKey; + }).mergeMap(function (path) { + return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey]) + .map(function (sequenceByKey) { + return sequenceByKey[path.sequenceKey]; + }); + }).combineLatest(this.configuration$, function (sequence, conf) { + var i = 0; + var instructionPlaces = []; + for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) { + var path = _a[_i]; + if (path.sequenceKey === sequence.key) { + var nodeInstructions = []; + var saveKey = false; + for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) { + var key = _c[_b]; + if (path.startKey === key) { + saveKey = true; + } + if (saveKey) { + var description = null; + for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) { + var infoKey = _e[_d]; + if (infoKey.key === key) { + description = infoKey.description; + } + } + nodeInstructions.push({ description: description, key: key }); + } + if (path.stopKey === key) { + saveKey = false; + } + } + instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i }); + } + i++; + } + return instructionPlaces; + }).scan(function (routeTrack, instructionPlaces) { + for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) { + var instructionPlace = instructionPlaces_1[_i]; + routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions; + } + routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered); + return routeTrack; + }, new RouteTrack()); + this._disposable = _slowedStream$ + .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) { + return { conf: conf, frame: frame, routeTrack: routeTrack }; + }).scan(function (routeState, rtAndFrame) { + if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) { + routeState.routeTrack = rtAndFrame.routeTrack; + routeState.currentNode = rtAndFrame.frame.state.currentNode; + routeState.lastNode = rtAndFrame.frame.state.lastNode; + routeState.playing = true; + } + else { + _this._navigator.stateService.cutNodes(); + routeState.playing = false; + } + return routeState; + }, new RouteState()) + .filter(function (routeState) { + return routeState.playing; + }).filter(function (routeState) { + for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) { + var nodeInstruction = _a[_i]; + if (!nodeInstruction) { + continue; + } + if (nodeInstruction.key === routeState.lastNode.key) { + return true; + } + } + return false; + }).distinctUntilChanged(undefined, function (routeState) { + return routeState.lastNode.key; + }).mergeMap(function (routeState) { + var i = 0; + for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) { + var nodeInstruction = _a[_i]; + if (nodeInstruction.key === routeState.lastNode.key) { + break; + } + i++; + } + var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1]; + if (!nextInstruction) { + return Observable_1.Observable.of(null); + } + return _this._navigator.graphService.cacheNode$(nextInstruction.key); + }).combineLatest(this.configuration$, function (node, conf) { + return { conf: conf, node: node }; + }).filter(function (cAN) { + return cAN.node !== null && cAN.conf.playing; + }).pluck("node").subscribe(this._navigator.stateService.appendNode$); + this._disposableDescription = this._navigator.stateService.currentNode$ + .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) { + if (conf.playing !== undefined && !conf.playing) { + return "quit"; + } + var description = null; + for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) { + var nodeInstruction = _a[_i]; + if (nodeInstruction.key === node.key) { + description = nodeInstruction.description; + break; + } + } + return description; + }).scan(function (descriptionState, description) { + if (description !== descriptionState.description && description !== null) { + descriptionState.description = description; + descriptionState.showsLeft = 6; + } + else { + descriptionState.showsLeft--; + } + if (description === "quit") { + descriptionState.description = null; + } + return descriptionState; + }, new DescriptionState()).map(function (descriptionState) { + if (descriptionState.showsLeft > 0 && descriptionState.description) { + return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) }; + } + else { + return { name: _this._name, vnode: vd.h("div", []) }; + } + }).subscribe(this._container.domRenderer.render$); }; - AttributionComponent.prototype._deactivate = function () { + RouteComponent.prototype._deactivate = function () { this._disposable.unsubscribe(); + this._disposableDescription.unsubscribe(); }; - AttributionComponent.prototype._getDefaultConfiguration = function () { + RouteComponent.prototype._getDefaultConfiguration = function () { return {}; }; - AttributionComponent.prototype._getAttributionNode = function (username, photoId) { - return vd.h("div.Attribution", {}, [ - vd.h("a", { href: "https://www.mapillary.com/app/user/" + username, - target: "_blank", - textContent: "@" + username, - }, []), - vd.h("span", { textContent: "|" }, []), - vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo", - target: "_blank", - textContent: "mapillary.com", - }, []), - ]); - }; - AttributionComponent.componentName = "attribution"; - return AttributionComponent; -}(Component_1.Component)); -exports.AttributionComponent = AttributionComponent; -Component_1.ComponentService.register(AttributionComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = AttributionComponent; - -},{"../Component":207,"virtual-dom":163}],219:[function(require,module,exports){ -/// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); -var Component_1 = require("../Component"); -var BackgroundComponent = (function (_super) { - __extends(BackgroundComponent, _super); - function BackgroundComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - } - BackgroundComponent.prototype._activate = function () { - this._container.domRenderer.render$ - .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") }); - }; - BackgroundComponent.prototype._deactivate = function () { - return; + RouteComponent.prototype.play = function () { + this.configure({ playing: true }); }; - BackgroundComponent.prototype._getDefaultConfiguration = function () { - return {}; + RouteComponent.prototype.stop = function () { + this.configure({ playing: false }); }; - BackgroundComponent.prototype._getBackgroundNode = function (notice) { - // todo: add condition for when to display the DOM node - return vd.h("div.BackgroundWrapper", {}, [ - vd.h("p", { textContent: notice }, []), + RouteComponent.prototype._getRouteAnnotationNode = function (description) { + return vd.h("div.RouteFrame", {}, [ + vd.h("p", { textContent: description }, []), ]); }; - BackgroundComponent.componentName = "background"; - return BackgroundComponent; + RouteComponent.componentName = "route"; + return RouteComponent; }(Component_1.Component)); -exports.BackgroundComponent = BackgroundComponent; -Component_1.ComponentService.register(BackgroundComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = BackgroundComponent; +exports.RouteComponent = RouteComponent; +Component_1.ComponentService.register(RouteComponent); +exports.default = RouteComponent; -},{"../Component":207,"virtual-dom":163}],220:[function(require,module,exports){ -/// +},{"../Component":290,"rxjs/Observable":29,"underscore":242,"virtual-dom":246}],316:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); var Component_1 = require("../Component"); -var BearingComponent = (function (_super) { - __extends(BearingComponent, _super); - function BearingComponent(name, container, navigator) { - _super.call(this, name, container, navigator); +var StatsComponent = /** @class */ (function (_super) { + __extends(StatsComponent, _super); + function StatsComponent(name, container, navigator) { + return _super.call(this, name, container, navigator) || this; } - BearingComponent.prototype._activate = function () { + StatsComponent.prototype._activate = function () { var _this = this; - this._renderSubscription = this._navigator.stateService.currentNode$ + this._sequenceSubscription = this._navigator.stateService.currentNode$ + .scan(function (keys, node) { + var sKey = node.sequenceKey; + keys.report = []; + if (!(sKey in keys.reported)) { + keys.report = [sKey]; + keys.reported[sKey] = true; + } + return keys; + }, { report: [], reported: {} }) + .filter(function (keys) { + return keys.report.length > 0; + }) + .mergeMap(function (keys) { + return _this._navigator.apiV3.sequenceViewAdd$(keys.report) + .catch(function (error, caught) { + console.error("Failed to report sequence stats (" + keys.report + ")", error); + return Observable_1.Observable.empty(); + }); + }) + .subscribe(function () { }); + this._imageSubscription = this._navigator.stateService.currentNode$ .map(function (node) { - return node.fullPano; + return node.key; }) - .map(function (pano) { - return { - name: _this._name, - vnode: pano ? vd.h("div.BearingIndicator", {}, []) : vd.h("div", {}, []), - }; + .buffer(this._navigator.stateService.currentNode$.debounceTime(5000)) + .scan(function (keys, newKeys) { + keys.report = []; + for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) { + var key = newKeys_1[_i]; + if (!(key in keys.reported)) { + keys.report.push(key); + keys.reported[key] = true; + } + } + return keys; + }, { report: [], reported: {} }) + .filter(function (keys) { + return keys.report.length > 0; }) - .subscribe(this._container.domRenderer.render$); + .mergeMap(function (keys) { + return _this._navigator.apiV3.imageViewAdd$(keys.report) + .catch(function (error, caught) { + console.error("Failed to report image stats (" + keys.report + ")", error); + return Observable_1.Observable.empty(); + }); + }) + .subscribe(function () { }); }; - BearingComponent.prototype._deactivate = function () { - this._renderSubscription.unsubscribe(); + StatsComponent.prototype._deactivate = function () { + this._sequenceSubscription.unsubscribe(); + this._imageSubscription.unsubscribe(); }; - BearingComponent.prototype._getDefaultConfiguration = function () { + StatsComponent.prototype._getDefaultConfiguration = function () { return {}; }; - BearingComponent.componentName = "bearing"; - return BearingComponent; + StatsComponent.componentName = "stats"; + return StatsComponent; }(Component_1.Component)); -exports.BearingComponent = BearingComponent; -Component_1.ComponentService.register(BearingComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = BearingComponent; +exports.StatsComponent = StatsComponent; +Component_1.ComponentService.register(StatsComponent); +exports.default = StatsComponent; -},{"../Component":207,"virtual-dom":163}],221:[function(require,module,exports){ +},{"../Component":290,"rxjs/Observable":29}],317:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/observable/merge"); -require("rxjs/add/observable/of"); -require("rxjs/add/observable/zip"); -require("rxjs/add/operator/distinct"); -require("rxjs/add/operator/expand"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/mergeAll"); -require("rxjs/add/operator/skip"); -require("rxjs/add/operator/switchMap"); -var Edge_1 = require("../Edge"); -var Component_1 = require("../Component"); -var CacheComponent = (function (_super) { - __extends(CacheComponent, _super); - function CacheComponent(name, container, navigator) { - _super.call(this, name, container, navigator); +var Subject_1 = require("rxjs/Subject"); +var Component_1 = require("../../Component"); +/** + * @class DirectionComponent + * @classdesc Component showing navigation arrows for steps and turns. + */ +var DirectionComponent = /** @class */ (function (_super) { + __extends(DirectionComponent, _super); + function DirectionComponent(name, container, navigator, directionDOMRenderer) { + var _this = _super.call(this, name, container, navigator) || this; + _this._renderer = !!directionDOMRenderer ? + directionDOMRenderer : + new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element); + _this._hoveredKeySubject$ = new Subject_1.Subject(); + _this._hoveredKey$ = _this._hoveredKeySubject$.share(); + return _this; } + Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", { + /** + * Get hovered key observable. + * + * @description An observable emitting the key of the node for the direction + * arrow that is being hovered. When the mouse leaves a direction arrow null + * is emitted. + * + * @returns {Observable} + */ + get: function () { + return this._hoveredKey$; + }, + enumerable: true, + configurable: true + }); + /** + * Set highlight key. + * + * @description The arrow pointing towards the node corresponding to the + * highlight key will be highlighted. + * + * @param {string} highlightKey Key of node to be highlighted if existing + * among arrows. + */ + DirectionComponent.prototype.setHighlightKey = function (highlightKey) { + this.configure({ highlightKey: highlightKey }); + }; + /** + * Set min width of container element. + * + * @description Set min width of the non transformed container element holding + * the navigation arrows. If the min width is larger than the max width the + * min width value will be used. + * + * The container element is automatically resized when the resize + * method on the Viewer class is called. + * + * @param {number} minWidth + */ + DirectionComponent.prototype.setMinWidth = function (minWidth) { + this.configure({ minWidth: minWidth }); + }; /** - * Set the cache depth. + * Set max width of container element. * - * Configures the cache depth. The cache depth can be different for - * different edge direction types. + * @description Set max width of the non transformed container element holding + * the navigation arrows. If the min width is larger than the max width the + * min width value will be used. * - * @param {ICacheDepth} depth - Cache depth structure. + * The container element is automatically resized when the resize + * method on the Viewer class is called. + * + * @param {number} minWidth */ - CacheComponent.prototype.setDepth = function (depth) { - this.configure({ depth: depth }); + DirectionComponent.prototype.setMaxWidth = function (maxWidth) { + this.configure({ maxWidth: maxWidth }); }; - CacheComponent.prototype._activate = function () { + /** @inheritdoc */ + DirectionComponent.prototype.resize = function () { + this._renderer.resize(this._container.element); + }; + DirectionComponent.prototype._activate = function () { var _this = this; - this._cacheSubscription = Observable_1.Observable - .combineLatest(this._navigator.stateService.currentNode$, this._configuration$) - .switchMap(function (nc) { - var node = nc[0]; - var configuration = nc[1]; - var depth = configuration.depth; - var sequenceDepth = Math.max(0, Math.min(4, depth.sequence)); - var panoDepth = Math.max(0, Math.min(2, depth.pano)); - var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step)); - var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn)); - var next$ = _this._cache$(node, Edge_1.EdgeDirection.Next, sequenceDepth); - var prev$ = _this._cache$(node, Edge_1.EdgeDirection.Prev, sequenceDepth); - var pano$ = _this._cache$(node, Edge_1.EdgeDirection.Pano, panoDepth); - var forward$ = _this._cache$(node, Edge_1.EdgeDirection.StepForward, stepDepth); - var backward$ = _this._cache$(node, Edge_1.EdgeDirection.StepBackward, stepDepth); - var left$ = _this._cache$(node, Edge_1.EdgeDirection.StepLeft, stepDepth); - var right$ = _this._cache$(node, Edge_1.EdgeDirection.StepRight, stepDepth); - var turnLeft$ = _this._cache$(node, Edge_1.EdgeDirection.TurnLeft, turnDepth); - var turnRight$ = _this._cache$(node, Edge_1.EdgeDirection.TurnRight, turnDepth); - var turnU$ = _this._cache$(node, Edge_1.EdgeDirection.TurnU, turnDepth); + this._configurationSubscription = this._configuration$ + .subscribe(function (configuration) { + _this._renderer.setConfiguration(configuration); + }); + this._nodeSubscription = this._navigator.stateService.currentNode$ + .do(function (node) { + _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) }); + _this._renderer.setNode(node); + }) + .withLatestFrom(this._configuration$) + .switchMap(function (_a) { + var node = _a[0], configuration = _a[1]; return Observable_1.Observable - .merge(next$, prev$, forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$); + .combineLatest(node.spatialEdges$, configuration.distinguishSequence ? + _this._navigator.graphService + .cacheSequence$(node.sequenceKey) + .catch(function (error, caught) { + console.error("Failed to cache sequence (" + node.sequenceKey + ")", error); + return Observable_1.Observable.of(null); + }) : + Observable_1.Observable.of(null)); }) - .subscribe(function (n) { return; }, function (e) { console.error(e); }); - }; - CacheComponent.prototype._deactivate = function () { - this._cacheSubscription.unsubscribe(); - }; - CacheComponent.prototype._getDefaultConfiguration = function () { - return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } }; - }; - CacheComponent.prototype._cache$ = function (node, direction, depth) { - var _this = this; - return Observable_1.Observable - .zip(this._nodeToEdges$(node, direction), Observable_1.Observable.of(depth)) - .expand(function (ed) { - var es = ed[0]; - var d = ed[1]; - var edgesDepths$ = []; - if (d > 0) { - for (var _i = 0, es_1 = es; _i < es_1.length; _i++) { - var edge = es_1[_i]; - if (edge.data.direction === direction) { - edgesDepths$.push(Observable_1.Observable - .zip(_this._navigator.graphService.cacheNode$(edge.to) - .mergeMap(function (n) { - return _this._nodeToEdges$(n, direction); - }), Observable_1.Observable.of(d - 1))); - } + .subscribe(function (_a) { + var edgeStatus = _a[0], sequence = _a[1]; + _this._renderer.setEdges(edgeStatus, sequence); + }); + this._renderCameraSubscription = this._container.renderService.renderCameraFrame$ + .do(function (renderCamera) { + _this._renderer.setRenderCamera(renderCamera); + }) + .map(function (renderCamera) { + return _this._renderer; + }) + .filter(function (renderer) { + return renderer.needsRender; + }) + .map(function (renderer) { + return { name: _this._name, vnode: renderer.render(_this._navigator) }; + }) + .subscribe(this._container.domRenderer.render$); + this._hoveredKeySubscription = Observable_1.Observable + .combineLatest([ + this._container.domRenderer.element$, + this._container.renderService.renderCamera$, + this._container.mouseService.mouseMove$.startWith(null), + this._container.mouseService.mouseUp$.startWith(null), + ], function (e, rc, mm, mu) { + return e; + }) + .map(function (element) { + var elements = element.getElementsByClassName("DirectionsPerspective"); + for (var i = 0; i < elements.length; i++) { + var hovered = elements.item(i).querySelector(":hover"); + if (hovered != null && hovered.hasAttribute("data-key")) { + return hovered.getAttribute("data-key"); } } - return Observable_1.Observable - .from(edgesDepths$) - .mergeAll(); + return null; }) - .skip(1); + .distinctUntilChanged() + .subscribe(this._hoveredKeySubject$); }; - CacheComponent.prototype._nodeToEdges$ = function (node, direction) { - return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ? - node.sequenceEdges$ : - node.spatialEdges$) - .first(function (status) { - return status.cached; - }) - .map(function (status) { - return status.edges; - }); + DirectionComponent.prototype._deactivate = function () { + this._configurationSubscription.unsubscribe(); + this._nodeSubscription.unsubscribe(); + this._renderCameraSubscription.unsubscribe(); + this._hoveredKeySubscription.unsubscribe(); }; - CacheComponent.componentName = "cache"; - return CacheComponent; + DirectionComponent.prototype._getDefaultConfiguration = function () { + return { + distinguishSequence: false, + maxWidth: 460, + minWidth: 260, + }; + }; + /** @inheritdoc */ + DirectionComponent.componentName = "direction"; + return DirectionComponent; }(Component_1.Component)); -exports.CacheComponent = CacheComponent; -Component_1.ComponentService.register(CacheComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = CacheComponent; +exports.DirectionComponent = DirectionComponent; +Component_1.ComponentService.register(DirectionComponent); +exports.default = DirectionComponent; -},{"../Component":207,"../Edge":208,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":46,"rxjs/add/operator/distinct":52,"rxjs/add/operator/expand":55,"rxjs/add/operator/map":60,"rxjs/add/operator/mergeAll":62,"rxjs/add/operator/skip":70,"rxjs/add/operator/switchMap":73}],222:[function(require,module,exports){ +},{"../../Component":290,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],318:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); -var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/startWith"); -var Utils_1 = require("../Utils"); -var Component = (function (_super) { - __extends(Component, _super); - function Component(name, container, navigator) { - _super.call(this); - this._activated$ = new BehaviorSubject_1.BehaviorSubject(false); - this._configurationSubject$ = new Subject_1.Subject(); - this._activated = false; - this._container = container; - this._name = name; - this._navigator = navigator; - this._configuration$ = - this._configurationSubject$ - .startWith(this.defaultConfiguration) - .scan(function (conf, newConf) { - for (var key in newConf) { - if (newConf.hasOwnProperty(key)) { - conf[key] = newConf[key]; - } - } - return conf; - }) - .publishReplay(1) - .refCount(); - this._configuration$.subscribe(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Geo_1 = require("../../Geo"); +/** + * @class DirectionDOMCalculator + * @classdesc Helper class for calculating DOM CSS properties. + */ +var DirectionDOMCalculator = /** @class */ (function () { + function DirectionDOMCalculator(configuration, element) { + this._spatial = new Geo_1.Spatial(); + this._minThresholdWidth = 320; + this._maxThresholdWidth = 1480; + this._minThresholdHeight = 240; + this._maxThresholdHeight = 820; + this._configure(configuration); + this._resize(element); + this._reset(); } - Object.defineProperty(Component.prototype, "activated", { + Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", { + get: function () { + return this._minWidth; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", { + get: function () { + return this._maxWidth; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", { + get: function () { + return this._containerWidth; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", { + get: function () { + return this._containerWidthCss; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", { + get: function () { + return this._containerMarginCss; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", { + get: function () { + return this._containerLeftCss; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", { + get: function () { + return this._containerHeight; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", { + get: function () { + return this._containerHeightCss; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", { + get: function () { + return this._containerBottomCss; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", { + get: function () { + return this._stepCircleSize; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", { get: function () { - return this._activated; + return this._stepCircleSizeCss; }, enumerable: true, configurable: true }); - Object.defineProperty(Component.prototype, "activated$", { + Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", { get: function () { - return this._activated$; + return this._stepCircleMarginCss; }, enumerable: true, configurable: true }); - Object.defineProperty(Component.prototype, "defaultConfiguration", { - /** - * Get default configuration. - * - * @returns {TConfiguration} Default configuration for component. - */ + Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", { get: function () { - return this._getDefaultConfiguration(); + return this._turnCircleSize; }, enumerable: true, configurable: true }); - Object.defineProperty(Component.prototype, "configuration$", { + Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", { get: function () { - return this._configuration$; + return this._turnCircleSizeCss; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", { + get: function () { + return this._outerRadius; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", { + get: function () { + return this._innerRadius; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", { + get: function () { + return this._shadowOffset; }, enumerable: true, configurable: true }); - Component.prototype.activate = function (conf) { - if (this._activated) { - return; - } - if (conf !== undefined) { - this._configurationSubject$.next(conf); - } - this._activate(); - this._activated = true; - this._activated$.next(true); - }; - ; - Component.prototype.configure = function (conf) { - this._configurationSubject$.next(conf); - }; - Component.prototype.deactivate = function () { - if (!this._activated) { - return; - } - this._deactivate(); - this._container.domRenderer.clear(this._name); - this._container.glRenderer.clear(this._name); - this._activated = false; - this._activated$.next(false); - }; - ; /** - * Detect the viewer's new width and height and resize the component's - * rendered elements accordingly if applicable. + * Configures the min and max width values. + * + * @param {IDirectionConfiguration} configuration Configuration + * with min and max width values. */ - Component.prototype.resize = function () { return; }; + DirectionDOMCalculator.prototype.configure = function (configuration) { + this._configure(configuration); + this._reset(); + }; /** - * Component name. Used when interacting with component through the Viewer's API. + * Resizes all properties according to the width and height + * of the element. + * + * @param {HTMLElement} element The container element from which to extract + * the width and height. */ - Component.componentName = "not_worthy"; - return Component; -}(Utils_1.EventEmitter)); -exports.Component = Component; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Component; - -},{"../Utils":215,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/startWith":72}],223:[function(require,module,exports){ -/// -"use strict"; -var _ = require("underscore"); -var Error_1 = require("../Error"); -var ComponentService = (function () { - function ComponentService(container, navigator) { - this._components = {}; - this._container = container; - this._navigator = navigator; - for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) { - var component = _a[_i]; - this._components[component.componentName] = { - active: false, - component: new component(component.componentName, container, navigator), - }; - } - this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator); - this._coverComponent.activate(); - this._coverActivated = true; - } - ComponentService.register = function (component) { - if (ComponentService.registeredComponents[component.componentName] === undefined) { - ComponentService.registeredComponents[component.componentName] = component; - } - }; - ComponentService.registerCover = function (coverComponent) { - ComponentService.registeredCoverComponent = coverComponent; - }; - ComponentService.prototype.activateCover = function () { - if (this._coverActivated) { - return; - } - this._coverActivated = true; - for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) { - var component = _a[_i]; - if (component.active) { - component.component.deactivate(); - } - } - return; - }; - ComponentService.prototype.deactivateCover = function () { - if (!this._coverActivated) { - return; - } - this._coverActivated = false; - for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) { - var component = _a[_i]; - if (component.active) { - component.component.activate(); - } - } - return; - }; - ComponentService.prototype.activate = function (name) { - this._checkName(name); - this._components[name].active = true; - if (!this._coverActivated) { - this.get(name).activate(); - } - }; - ComponentService.prototype.configure = function (name, conf) { - this._checkName(name); - this.get(name).configure(conf); - }; - ComponentService.prototype.deactivate = function (name) { - this._checkName(name); - this._components[name].active = false; - if (!this._coverActivated) { - this.get(name).deactivate(); - } - }; - ComponentService.prototype.resize = function () { - for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) { - var component = _a[_i]; - component.component.resize(); - } - }; - ComponentService.prototype.get = function (name) { - return this._components[name].component; - }; - ComponentService.prototype.getCover = function () { - return this._coverComponent; - }; - ComponentService.prototype._checkName = function (name) { - if (!(name in this._components)) { - throw new Error_1.ParameterMapillaryError("Component does not exist: " + name); - } - }; - ComponentService.registeredComponents = {}; - return ComponentService; -}()); -exports.ComponentService = ComponentService; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ComponentService; - -},{"../Error":209,"underscore":158}],224:[function(require,module,exports){ -/// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/withLatestFrom"); -var Component_1 = require("../Component"); -var CoverComponent = (function (_super) { - __extends(CoverComponent, _super); - function CoverComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - } - CoverComponent.prototype._activate = function () { - var _this = this; - this._keyDisposable = this._navigator.stateService.currentNode$ - .withLatestFrom(this._configuration$, function (node, configuration) { - return [node, configuration]; - }) - .filter(function (nc) { - return nc[0].key !== nc[1].key; - }) - .map(function (nc) { return nc[0]; }) - .map(function (node) { - return { key: node.key, src: node.image.src }; - }) - .subscribe(this._configurationSubject$); - this._disposable = this._configuration$ - .map(function (conf) { - if (!conf.key) { - return { name: _this._name, vnode: vd.h("div", []) }; - } - if (!conf.visible) { - return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) }; - } - return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) }; - }) - .subscribe(this._container.domRenderer.render$); - }; - CoverComponent.prototype._deactivate = function () { - this._disposable.unsubscribe(); - this._keyDisposable.unsubscribe(); - }; - CoverComponent.prototype._getDefaultConfiguration = function () { - return { "loading": false, "visible": true }; - }; - CoverComponent.prototype._getCoverButtonVNode = function (conf) { - var _this = this; - var cover = conf.loading ? "div.Cover.CoverLoading" : "div.Cover"; - return vd.h(cover, [ - this._getCoverBackgroundVNode(conf), - vd.h("button.CoverButton", { onclick: function () { _this.configure({ loading: true }); } }, ["Explore"]), - vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []), - ]); - }; - CoverComponent.prototype._getCoverBackgroundVNode = function (conf) { - var url = conf.src != null ? - "url(" + conf.src + ")" : - "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)"; - var properties = { style: { backgroundImage: url } }; - var children = []; - if (conf.loading) { - children.push(vd.h("div.Spinner", {}, [])); - } - children.push(vd.h("div.CoverBackgroundGradient", {}, [])); - return vd.h("div.CoverBackground", properties, children); - }; - CoverComponent.componentName = "cover"; - return CoverComponent; -}(Component_1.Component)); -exports.CoverComponent = CoverComponent; -Component_1.ComponentService.registerCover(CoverComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = CoverComponent; - -},{"../Component":207,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/withLatestFrom":76,"virtual-dom":163}],225:[function(require,module,exports){ -/// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var _ = require("underscore"); -var vd = require("virtual-dom"); -var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); -require("rxjs/add/operator/combineLatest"); -var Component_1 = require("../Component"); -var DebugComponent = (function (_super) { - __extends(DebugComponent, _super); - function DebugComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._open$ = new BehaviorSubject_1.BehaviorSubject(false); - this._displaying = false; - } - DebugComponent.prototype._activate = function () { - var _this = this; - this._disposable = this._navigator.stateService.currentState$ - .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) { - return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) }; - }) - .subscribe(this._container.domRenderer.render$); + DirectionDOMCalculator.prototype.resize = function (element) { + this._resize(element); + this._reset(); }; - DebugComponent.prototype._deactivate = function () { - this._disposable.unsubscribe(); + /** + * Calculates the coordinates on the unit circle for an angle. + * + * @param {number} angle Angle in radians. + * @returns {Array} The x and y coordinates on the unit circle. + */ + DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) { + return [Math.cos(angle), Math.sin(angle)]; }; - DebugComponent.prototype._getDefaultConfiguration = function () { - return {}; + /** + * Calculates the coordinates on the unit circle for the + * relative angle between the first and second angle. + * + * @param {number} first Angle in radians. + * @param {number} second Angle in radians. + * @returns {Array} The x and y coordinates on the unit circle + * for the relative angle between the first and second angle. + */ + DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) { + var relativeAngle = this._spatial.wrapAngle(first - second); + return this.angleToCoordinates(relativeAngle); }; - DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) { - var ret = []; - ret.push(vd.h("h2", "Node")); - if (frame.state.currentNode) { - ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key)); - } - if (frame.state.previousNode) { - ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key)); - } - ret.push(vd.h("h2", "Loading")); - var total = 0; - var loaded = 0; - var loading = 0; - for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) { - var loadStat = _a[_i]; - total += loadStat.loaded; - if (loadStat.loaded !== loadStat.total) { - loading++; - } - else { - loaded++; - } - } - ret.push(vd.h("p", "Loaded Images: " + loaded)); - ret.push(vd.h("p", "Loading Images: " + loading)); - ret.push(vd.h("p", "Total bytes loaded: " + total)); - ret.push(vd.h("h2", "Camera")); - ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x)); - ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y)); - ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z)); - ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x)); - ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y)); - ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z)); - ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x)); - ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y)); - ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z)); - return ret; + DirectionDOMCalculator.prototype._configure = function (configuration) { + this._minWidth = configuration.minWidth; + this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth); }; - DebugComponent.prototype._getDebugVNode = function (open, info) { - if (open) { - return vd.h("div.Debug", {}, [ - vd.h("h2", {}, ["Debug"]), - this._getDebugVNodeButton(open), - vd.h("pre", {}, info), - ]); - } - else { - return this._getDebugVNodeButton(open); - } + DirectionDOMCalculator.prototype._resize = function (element) { + this._elementWidth = element.offsetWidth; + this._elementHeight = element.offsetHeight; }; - DebugComponent.prototype._getDebugVNodeButton = function (open) { - var buttonText = open ? "Disable Debug" : "D"; - var buttonCssClass = open ? "" : ".DebugButtonFixed"; - if (open) { - return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]); - } - else { - return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]); - } + DirectionDOMCalculator.prototype._reset = function () { + this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight); + this._containerHeight = this._getContainerHeight(this.containerWidth); + this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight); + this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight); + this._outerRadius = this._getOuterRadius(this._containerHeight); + this._innerRadius = this._getInnerRadius(this._containerHeight); + this._shadowOffset = 3; + this._containerWidthCss = this._numberToCssPixels(this._containerWidth); + this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth); + this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth)); + this._containerHeightCss = this._numberToCssPixels(this._containerHeight); + this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight)); + this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize); + this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize); + this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize); }; - DebugComponent.prototype._closeDebugElement = function (open) { - this._open$.next(false); + DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) { + var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth); + var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight); + var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight))); + coeff = 0.04 * Math.round(25 * coeff); + return this._minWidth + coeff * (this._maxWidth - this._minWidth); }; - DebugComponent.prototype._openDebugElement = function () { - this._open$.next(true); + DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) { + return 0.77 * containerWidth; }; - DebugComponent.componentName = "debug"; - return DebugComponent; -}(Component_1.Component)); -exports.DebugComponent = DebugComponent; -Component_1.ComponentService.register(DebugComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = DebugComponent; - -},{"../Component":207,"rxjs/BehaviorSubject":25,"rxjs/add/operator/combineLatest":49,"underscore":158,"virtual-dom":163}],226:[function(require,module,exports){ -/// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); -require("rxjs/add/operator/combineLatest"); -var Component_1 = require("../Component"); -var ImageComponent = (function (_super) { - __extends(ImageComponent, _super); - function ImageComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._canvasId = container.id + "-" + this._name; - } - ImageComponent.prototype._activate = function () { - var _this = this; - this.drawSubscription = this._container.domRenderer.element$ - .combineLatest(this._navigator.stateService.currentNode$, function (element, node) { - var canvas = document.getElementById(_this._canvasId); - return { canvas: canvas, node: node }; - }) - .subscribe(function (canvasNode) { - var canvas = canvasNode.canvas; - var node = canvasNode.node; - if (!node || !canvas) { - return null; - } - var adaptableDomRenderer = canvas.parentElement; - var width = adaptableDomRenderer.offsetWidth; - var height = adaptableDomRenderer.offsetHeight; - canvas.width = width; - canvas.height = height; - var ctx = canvas.getContext("2d"); - ctx.drawImage(node.image, 0, 0, width, height); - }); - this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) }); + DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) { + return 0.34 * containerHeight; }; - ImageComponent.prototype._deactivate = function () { - this.drawSubscription.unsubscribe(); + DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) { + return 0.3 * containerHeight; }; - ImageComponent.prototype._getDefaultConfiguration = function () { - return {}; + DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) { + return 0.31 * containerHeight; }; - ImageComponent.componentName = "image"; - return ImageComponent; -}(Component_1.Component)); -exports.ImageComponent = ImageComponent; -Component_1.ComponentService.register(ImageComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ImageComponent; + DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) { + return 0.125 * containerHeight; + }; + DirectionDOMCalculator.prototype._numberToCssPixels = function (value) { + return value + "px"; + }; + DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) { + return value > minWidth ? value : minWidth; + }; + return DirectionDOMCalculator; +}()); +exports.DirectionDOMCalculator = DirectionDOMCalculator; +exports.default = DirectionDOMCalculator; -},{"../Component":207,"rxjs/add/operator/combineLatest":49,"virtual-dom":163}],227:[function(require,module,exports){ +},{"../../Geo":293}],319:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/observable/fromEvent"); -require("rxjs/add/operator/withLatestFrom"); -var Edge_1 = require("../Edge"); -var Component_1 = require("../Component"); -var Geo_1 = require("../Geo"); -var KeyboardComponent = (function (_super) { - __extends(KeyboardComponent, _super); - function KeyboardComponent(name, container, navigator) { - _super.call(this, name, container, navigator); +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Component_1 = require("../../Component"); +var Edge_1 = require("../../Edge"); +var Error_1 = require("../../Error"); +var Geo_1 = require("../../Geo"); +/** + * @class DirectionDOMRenderer + * @classdesc DOM renderer for direction arrows. + */ +var DirectionDOMRenderer = /** @class */ (function () { + function DirectionDOMRenderer(configuration, element) { + this._isEdge = false; this._spatial = new Geo_1.Spatial(); - this._perspectiveDirections = [ + this._calculator = new Component_1.DirectionDOMCalculator(configuration, element); + this._node = null; + this._rotation = { phi: 0, theta: 0 }; + this._epsilon = 0.5 * Math.PI / 180; + this._highlightKey = null; + this._distinguishSequence = false; + this._needsRender = false; + this._stepEdges = []; + this._turnEdges = []; + this._panoEdges = []; + this._sequenceEdgeKeys = []; + this._stepDirections = [ Edge_1.EdgeDirection.StepForward, Edge_1.EdgeDirection.StepBackward, Edge_1.EdgeDirection.StepLeft, Edge_1.EdgeDirection.StepRight, + ]; + this._turnDirections = [ Edge_1.EdgeDirection.TurnLeft, Edge_1.EdgeDirection.TurnRight, Edge_1.EdgeDirection.TurnU, ]; + this._turnNames = {}; + this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft"; + this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight"; + this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround"; + // detects IE 8-11, then Edge 20+. + var isIE = !!document.documentMode; + this._isEdge = !isIE && !!window.StyleMedia; } - KeyboardComponent.prototype._activate = function () { - var _this = this; - var sequenceEdges$ = this._navigator.stateService.currentNode$ - .switchMap(function (node) { - return node.sequenceEdges$; - }); - var spatialEdges$ = this._navigator.stateService.currentNode$ - .switchMap(function (node) { - return node.spatialEdges$; - }); - this._disposable = Observable_1.Observable - .fromEvent(document, "keydown") - .withLatestFrom(this._navigator.stateService.currentState$, sequenceEdges$, spatialEdges$, function (event, frame, sequenceEdges, spatialEdges) { - return { event: event, frame: frame, sequenceEdges: sequenceEdges, spatialEdges: spatialEdges }; - }) - .subscribe(function (kf) { - if (!kf.frame.state.currentNode.pano) { - _this._navigatePerspective(kf.event, kf.sequenceEdges, kf.spatialEdges); - } - else { - _this._navigatePanorama(kf.event, kf.sequenceEdges, kf.spatialEdges, kf.frame.state.camera); - } - }); + Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", { + /** + * Get needs render. + * + * @returns {boolean} Value indicating whether render should be called. + */ + get: function () { + return this._needsRender; + }, + enumerable: true, + configurable: true + }); + /** + * Renders virtual DOM elements. + * + * @description Calling render resets the needs render property. + */ + DirectionDOMRenderer.prototype.render = function (navigator) { + this._needsRender = false; + var rotation = this._rotation; + var steps = []; + var turns = []; + if (this._node.pano) { + steps = steps.concat(this._createPanoArrows(navigator, rotation)); + } + else { + steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation)); + steps = steps.concat(this._createStepArrows(navigator, rotation)); + turns = turns.concat(this._createTurnArrows(navigator)); + } + return this._getContainer(steps, turns, rotation); }; - KeyboardComponent.prototype._deactivate = function () { - this._disposable.unsubscribe(); + DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) { + this._setEdges(edgeStatus, sequence); + this._setNeedsRender(); }; - KeyboardComponent.prototype._getDefaultConfiguration = function () { - return {}; + /** + * Set node for which to show edges. + * + * @param {Node} node + */ + DirectionDOMRenderer.prototype.setNode = function (node) { + this._node = node; + this._clearEdges(); + this._setNeedsRender(); }; - KeyboardComponent.prototype._navigatePanorama = function (event, sequenceEdges, spatialEdges, camera) { - var navigationAngle = 0; - var stepDirection = null; - var sequenceDirection = null; - var phi = this._rotationFromCamera(camera).phi; - switch (event.keyCode) { - case 37: - if (event.shiftKey || event.altKey) { - break; - } - navigationAngle = Math.PI / 2 + phi; - stepDirection = Edge_1.EdgeDirection.StepLeft; - break; - case 38: - if (event.shiftKey) { - break; - } - if (event.altKey) { - sequenceDirection = Edge_1.EdgeDirection.Next; - break; - } - navigationAngle = phi; - stepDirection = Edge_1.EdgeDirection.StepForward; - break; - case 39: - if (event.shiftKey || event.altKey) { - break; - } - navigationAngle = -Math.PI / 2 + phi; - stepDirection = Edge_1.EdgeDirection.StepRight; - break; - case 40: - if (event.shiftKey) { - break; - } - if (event.altKey) { - sequenceDirection = Edge_1.EdgeDirection.Prev; - break; - } - navigationAngle = Math.PI + phi; - stepDirection = Edge_1.EdgeDirection.StepBackward; - break; - default: - return; - } - event.preventDefault(); - if (sequenceDirection != null) { - this._moveInDir(sequenceDirection, sequenceEdges); + /** + * Set the render camera to use for calculating rotations. + * + * @param {RenderCamera} renderCamera + */ + DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) { + var rotation = renderCamera.rotation; + if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) { return; } - if (stepDirection == null || !spatialEdges.cached) { - return; + this._rotation = rotation; + this._setNeedsRender(); + }; + /** + * Set configuration values. + * + * @param {IDirectionConfiguration} configuration + */ + DirectionDOMRenderer.prototype.setConfiguration = function (configuration) { + var needsRender = false; + if (this._highlightKey !== configuration.highlightKey || + this._distinguishSequence !== configuration.distinguishSequence) { + this._highlightKey = configuration.highlightKey; + this._distinguishSequence = configuration.distinguishSequence; + needsRender = true; } - navigationAngle = this._spatial.wrapAngle(navigationAngle); - var threshold = Math.PI / 4; - var edges = spatialEdges.edges.filter(function (e) { - return e.data.direction === Edge_1.EdgeDirection.Pano || - e.data.direction === stepDirection; - }); - var smallestAngle = Number.MAX_VALUE; - var toKey = null; - for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) { - var edge = edges_1[_i]; - var angle = Math.abs(this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle)); - if (angle < Math.min(smallestAngle, threshold)) { - smallestAngle = angle; - toKey = edge.to; - } + if (this._calculator.minWidth !== configuration.minWidth || + this._calculator.maxWidth !== configuration.maxWidth) { + this._calculator.configure(configuration); + needsRender = true; } - if (toKey == null) { - return; + if (needsRender) { + this._setNeedsRender(); } - this._navigator.moveToKey$(toKey) - .subscribe(function (n) { return; }, function (e) { console.error(e); }); }; - KeyboardComponent.prototype._rotationFromCamera = function (camera) { - var direction = camera.lookat.clone().sub(camera.position); - var upProjection = direction.clone().dot(camera.up); - var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection)); - var phi = Math.atan2(planeProjection.y, planeProjection.x); - var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]); - return { phi: phi, theta: theta }; + /** + * Detect the element's width and height and resize + * elements accordingly. + * + * @param {HTMLElement} element Viewer container element. + */ + DirectionDOMRenderer.prototype.resize = function (element) { + this._calculator.resize(element); + this._setNeedsRender(); }; - KeyboardComponent.prototype._navigatePerspective = function (event, sequenceEdges, spatialEdges) { - var direction = null; - var sequenceDirection = null; - switch (event.keyCode) { - case 37: - if (event.altKey) { - break; - } - direction = event.shiftKey ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft; - break; - case 38: - if (event.altKey) { - sequenceDirection = Edge_1.EdgeDirection.Next; - break; + DirectionDOMRenderer.prototype._setNeedsRender = function () { + if (this._node != null) { + this._needsRender = true; + } + }; + DirectionDOMRenderer.prototype._clearEdges = function () { + this._stepEdges = []; + this._turnEdges = []; + this._panoEdges = []; + this._sequenceEdgeKeys = []; + }; + DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) { + this._stepEdges = []; + this._turnEdges = []; + this._panoEdges = []; + this._sequenceEdgeKeys = []; + for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { + var edge = _a[_i]; + var direction = edge.data.direction; + if (this._stepDirections.indexOf(direction) > -1) { + this._stepEdges.push(edge); + continue; + } + if (this._turnDirections.indexOf(direction) > -1) { + this._turnEdges.push(edge); + continue; + } + if (edge.data.direction === Edge_1.EdgeDirection.Pano) { + this._panoEdges.push(edge); + } + } + if (this._distinguishSequence && sequence != null) { + var edges = this._panoEdges + .concat(this._stepEdges) + .concat(this._turnEdges); + for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) { + var edge = edges_1[_b]; + var edgeKey = edge.to; + for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) { + var sequenceKey = _d[_c]; + if (sequenceKey === edgeKey) { + this._sequenceEdgeKeys.push(edgeKey); + break; + } } - direction = event.shiftKey ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward; + } + } + }; + DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) { + var arrows = []; + for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) { + var panoEdge = _a[_i]; + arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano")); + } + for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) { + var stepEdge = _c[_b]; + arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction)); + } + return arrows; + }; + DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) { + var threshold = Math.PI / 8; + var relativePhi = rotation.phi; + switch (direction) { + case Edge_1.EdgeDirection.StepBackward: + relativePhi = rotation.phi - Math.PI; break; - case 39: - if (event.altKey) { - break; - } - direction = event.shiftKey ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight; + case Edge_1.EdgeDirection.StepLeft: + relativePhi = rotation.phi + Math.PI / 2; break; - case 40: - if (event.altKey) { - sequenceDirection = Edge_1.EdgeDirection.Prev; - break; - } - direction = event.shiftKey ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward; + case Edge_1.EdgeDirection.StepRight: + relativePhi = rotation.phi - Math.PI / 2; break; default: - return; + break; } - event.preventDefault(); - if (sequenceDirection != null) { - this._moveInDir(sequenceDirection, sequenceEdges); - return; + if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) { + return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep"); } - this._moveInDir(direction, spatialEdges); + return this._createVNodeDisabled(key, azimuth, rotation); }; - KeyboardComponent.prototype._moveInDir = function (direction, edgeStatus) { - if (!edgeStatus.cached) { - return; + DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) { + var arrows = []; + for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) { + var panoEdge = _a[_i]; + arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true)); } - for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { - var edge = _a[_i]; - if (edge.data.direction === direction) { - this._navigator.moveToKey$(edge.to) - .subscribe(function (n) { return; }, function (e) { console.error(e); }); - return; - } + return arrows; + }; + DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) { + var arrows = []; + for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) { + var stepEdge = _a[_i]; + arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction)); } + return arrows; }; - KeyboardComponent.componentName = "keyboard"; - return KeyboardComponent; -}(Component_1.Component)); -exports.KeyboardComponent = KeyboardComponent; -Component_1.ComponentService.register(KeyboardComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = KeyboardComponent; - -},{"../Component":207,"../Edge":208,"../Geo":210,"rxjs/Observable":28,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/withLatestFrom":76}],228:[function(require,module,exports){ -/// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var _ = require("underscore"); -var vd = require("virtual-dom"); -require("rxjs/add/operator/combineLatest"); -var Component_1 = require("../Component"); -var LoadingComponent = (function (_super) { - __extends(LoadingComponent, _super); - function LoadingComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - } - LoadingComponent.prototype._activate = function () { - var _this = this; - this._loadingSubscription = this._navigator.loadingService.loading$ - .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) { - if (!loading) { - return { name: "loading", vnode: _this._getBarVNode(100) }; - } - var total = 0; - var loaded = 0; - for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) { - var loadStat = _a[_i]; - if (loadStat.loaded !== loadStat.total) { - loaded += loadStat.loaded; - total += loadStat.total; + DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) { + var turns = []; + for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) { + var turnEdge = _a[_i]; + var direction = turnEdge.data.direction; + var name_1 = this._turnNames[direction]; + turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction)); + } + return turns; + }; + DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) { + var onClick = function (e) { + navigator.moveToKey$(key) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); } - } - var percentage = 100; - if (total !== 0) { - percentage = (loaded / total) * 100; - } - return { name: _this._name, vnode: _this._getBarVNode(percentage) }; - }) - .subscribe(this._container.domRenderer.render$); + }); + }; + return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically); + }; + DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) { + var onClick = function (e) { + navigator.moveDir$(direction) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); + } + }); + }; + return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick); }; - LoadingComponent.prototype._deactivate = function () { - this._loadingSubscription.unsubscribe(); + DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) { + var onClick = function (e) { + navigator.moveDir$(direction) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); + } + }); + }; + var style = { + height: this._calculator.turnCircleSizeCss, + transform: "rotate(0)", + width: this._calculator.turnCircleSizeCss, + }; + switch (direction) { + case Edge_1.EdgeDirection.TurnLeft: + style.left = "5px"; + style.top = "5px"; + break; + case Edge_1.EdgeDirection.TurnRight: + style.right = "5px"; + style.top = "5px"; + break; + case Edge_1.EdgeDirection.TurnU: + style.left = "5px"; + style.bottom = "5px"; + break; + default: + break; + } + var circleProperties = { + attributes: { + "data-key": key, + }, + onclick: onClick, + style: style, + }; + var circleClassName = "TurnCircle"; + if (this._sequenceEdgeKeys.indexOf(key) > -1) { + circleClassName += "Sequence"; + } + if (this._highlightKey === key) { + circleClassName += "Highlight"; + } + var turn = vd.h("div." + className, {}, []); + return vd.h("div." + circleClassName, circleProperties, [turn]); }; - LoadingComponent.prototype._getDefaultConfiguration = function () { - return {}; + DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) { + return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled"); }; - LoadingComponent.prototype._getBarVNode = function (percentage) { - var loadingBarStyle = {}; - var loadingContainerStyle = {}; - if (percentage !== 100) { - loadingBarStyle.width = percentage.toFixed(0) + "%"; - loadingBarStyle.opacity = "1"; + DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) { + var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi); + // rotate 90 degrees clockwise and flip over X-axis + var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth); + var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight); + var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi); + var shadowOffset = this._calculator.shadowOffset; + var shadowTranslationX = -shadowOffset * shadowTranslation[1]; + var shadowTranslationY = shadowOffset * shadowTranslation[0]; + var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))"; + var properties = { + style: { + "-webkit-filter": filter, + filter: filter, + }, + }; + var chevron = vd.h("div." + className, properties, []); + var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi); + var circleTransform = shiftVertically ? + "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" : + "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)"; + var circleProperties = { + attributes: { "data-key": key }, + onclick: onClick, + style: { + height: this._calculator.stepCircleSizeCss, + marginLeft: this._calculator.stepCircleMarginCss, + marginTop: this._calculator.stepCircleMarginCss, + transform: circleTransform, + width: this._calculator.stepCircleSizeCss, + }, + }; + if (this._sequenceEdgeKeys.indexOf(key) > -1) { + circleClassName += "Sequence"; } - else { - loadingBarStyle.width = "100%"; - loadingBarStyle.opacity = "0"; + if (this._highlightKey === key) { + circleClassName += "Highlight"; } - return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]); + return vd.h("div." + circleClassName, circleProperties, [chevron]); }; - LoadingComponent.componentName = "loading"; - return LoadingComponent; -}(Component_1.Component)); -exports.LoadingComponent = LoadingComponent; -Component_1.ComponentService.register(LoadingComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = LoadingComponent; + DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) { + // edge does not handle hover on perspective transforms. + var transform = this._isEdge ? + "rotateX(60deg)" : + "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)"; + var properties = { + oncontextmenu: function (event) { event.preventDefault(); }, + style: { + bottom: this._calculator.containerBottomCss, + height: this._calculator.containerHeightCss, + left: this._calculator.containerLeftCss, + marginLeft: this._calculator.containerMarginCss, + transform: transform, + width: this._calculator.containerWidthCss, + }, + }; + return vd.h("div.DirectionsPerspective", properties, turns.concat(steps)); + }; + return DirectionDOMRenderer; +}()); +exports.DirectionDOMRenderer = DirectionDOMRenderer; +exports.default = DirectionDOMRenderer; -},{"../Component":207,"rxjs/add/operator/combineLatest":49,"underscore":158,"virtual-dom":163}],229:[function(require,module,exports){ -/// +},{"../../Component":290,"../../Edge":291,"../../Error":292,"../../Geo":293,"virtual-dom":246}],320:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var THREE = require("three"); -var vd = require("virtual-dom"); +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/observable/merge"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/withLatestFrom"); -var Component_1 = require("../Component"); -var Geo_1 = require("../Geo"); -/** - * @class MouseComponent - * @classdesc Component handling mouse and touch events for camera movement. - */ -var MouseComponent = (function (_super) { - __extends(MouseComponent, _super); - function MouseComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._spatial = new Geo_1.Spatial(); - } - MouseComponent.prototype._activate = function () { - var _this = this; - var draggingStarted$ = this._container.mouseService - .filtered$(this._name, this._container.mouseService.mouseDragStart$) - .map(function (event) { - return true; - }); - var draggingStopped$ = this._container.mouseService - .filtered$(this._name, this._container.mouseService.mouseDragEnd$) - .map(function (event) { - return false; - }); - var dragging$ = Observable_1.Observable - .merge(draggingStarted$, draggingStopped$) - .startWith(false) - .share(); - this._activeSubscription = dragging$ - .subscribe(this._container.mouseService.activate$); - this._cursorSubscription = dragging$ - .map(function (dragging) { - var className = dragging ? "MouseContainerGrabbing" : "MouseContainerGrab"; - var vNode = vd.h("div." + className, {}, []); - return { name: _this._name, vnode: vNode }; +var Subject_1 = require("rxjs/Subject"); +var Component_1 = require("../../Component"); +var Render_1 = require("../../Render"); +var Tiles_1 = require("../../Tiles"); +var Utils_1 = require("../../Utils"); +var ImagePlaneComponent = /** @class */ (function (_super) { + __extends(ImagePlaneComponent, _super); + function ImagePlaneComponent(name, container, navigator) { + var _this = _super.call(this, name, container, navigator) || this; + _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin); + _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator(); + _this._rendererOperation$ = new Subject_1.Subject(); + _this._rendererCreator$ = new Subject_1.Subject(); + _this._rendererDisposer$ = new Subject_1.Subject(); + _this._renderer$ = _this._rendererOperation$ + .scan(function (renderer, operation) { + return operation(renderer); + }, null) + .filter(function (renderer) { + return renderer != null; }) - .subscribe(this._container.domRenderer.render$); - var mouseMovement$ = this._container.mouseService - .filtered$(this._name, this._container.mouseService.mouseDrag$) - .map(function (e) { - return { - clientX: e.clientX, - clientY: e.clientY, - movementX: e.movementX, - movementY: e.movementY, - }; + .distinctUntilChanged(undefined, function (renderer) { + return renderer.frameId; }); - var touchMovement$ = this._container.touchService.singleTouchMove$ - .map(function (touch) { - return { - clientX: touch.clientX, - clientY: touch.clientY, - movementX: touch.movementX, - movementY: touch.movementY, + _this._rendererCreator$ + .map(function () { + return function (renderer) { + if (renderer != null) { + throw new Error("Multiple image plane states can not be created at the same time"); + } + return new Component_1.ImagePlaneGLRenderer(); }; - }); - this._movementSubscription = Observable_1.Observable - .merge(mouseMovement$, touchMovement$) - .withLatestFrom(this._navigator.stateService.currentState$, function (m, f) { - return [m, f]; }) - .filter(function (args) { - var state = args[1].state; - return state.currentNode.fullPano || state.nodesAhead < 1; - }) - .map(function (args) { - return args[0]; + .subscribe(_this._rendererOperation$); + _this._rendererDisposer$ + .map(function () { + return function (renderer) { + renderer.dispose(); + return null; + }; }) - .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$, function (m, r, t, c) { - return [m, r, t, c]; + .subscribe(_this._rendererOperation$); + return _this; + } + ImagePlaneComponent.prototype._activate = function () { + var _this = this; + this._rendererSubscription = this._renderer$ + .map(function (renderer) { + var renderHash = { + name: _this._name, + render: { + frameId: renderer.frameId, + needsRender: renderer.needsRender, + render: renderer.render.bind(renderer), + stage: Render_1.GLRenderStage.Background, + }, + }; + renderer.clearNeedsRender(); + return renderHash; }) - .map(function (args) { - var movement = args[0]; - var render = args[1]; - var transform = args[2]; - var camera = args[3].clone(); - var element = _this._container.element; - var offsetWidth = element.offsetWidth; - var offsetHeight = element.offsetHeight; - var clientRect = element.getBoundingClientRect(); - var canvasX = movement.clientX - clientRect.left; - var canvasY = movement.clientY - clientRect.top; - var currentDirection = _this._unproject(canvasX, canvasY, offsetWidth, offsetHeight, render.perspective) - .sub(render.perspective.position); - var directionX = _this._unproject(canvasX - movement.movementX, canvasY, offsetWidth, offsetHeight, render.perspective) - .sub(render.perspective.position); - var directionY = _this._unproject(canvasX, canvasY - movement.movementY, offsetWidth, offsetHeight, render.perspective) - .sub(render.perspective.position); - var deltaPhi = (movement.movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection); - var deltaTheta = (movement.movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection); - var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1)); - var upQuaternionInverse = upQuaternion.clone().inverse(); - var offset = new THREE.Vector3(); - offset.copy(camera.lookat).sub(camera.position); - offset.applyQuaternion(upQuaternion); - var length = offset.length(); - var phi = Math.atan2(offset.y, offset.x); - phi += deltaPhi; - var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z); - theta += deltaTheta; - theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta)); - offset.x = Math.sin(theta) * Math.cos(phi); - offset.y = Math.sin(theta) * Math.sin(phi); - offset.z = Math.cos(theta); - offset.applyQuaternion(upQuaternionInverse); - var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length)); - var basic = transform.projectBasic(lookat.toArray()); - var original = transform.projectBasic(camera.lookat.toArray()); - var x = basic[0] - original[0]; - var y = basic[1] - original[1]; - if (Math.abs(x) > 1) { - x = 0; - } - else if (x > 0.5) { - x = x - 1; - } - else if (x < -0.5) { - x = x + 1; - } - return [x, y]; + .subscribe(this._container.glRenderer.render$); + this._rendererCreator$.next(null); + this._stateSubscription = this._navigator.stateService.currentState$ + .map(function (frame) { + return function (renderer) { + renderer.updateFrame(frame); + return renderer; + }; }) - .subscribe(function (basicRotation) { - _this._navigator.stateService.rotateBasic(basicRotation); - }); - this._mouseWheelSubscription = this._container.mouseService - .filtered$(this._name, this._container.mouseService.mouseWheel$) - .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) { - return [w, f]; + .subscribe(this._rendererOperation$); + var textureProvider$ = this._navigator.stateService.currentState$ + .distinctUntilChanged(undefined, function (frame) { + return frame.state.currentNode.key; }) + .combineLatest(this._configuration$) .filter(function (args) { - var state = args[1].state; - return state.currentNode.fullPano || state.nodesAhead < 1; + return args[1].imageTiling === true; }) .map(function (args) { return args[0]; }) - .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) { - return [w, r, t]; + .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$) + .map(function (_a) { + var frame = _a[0], renderer = _a[1], size = _a[2]; + var state = frame.state; + var viewportSize = Math.max(size.width, size.height); + var currentNode = state.currentNode; + var currentTransform = state.currentTransform; + var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512; + return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer); + }) + .publishReplay(1) + .refCount(); + this._textureProviderSubscription = textureProvider$.subscribe(function () { }); + this._setTextureProviderSubscription = textureProvider$ + .map(function (provider) { + return function (renderer) { + renderer.setTextureProvider(provider.key, provider); + return renderer; + }; + }) + .subscribe(this._rendererOperation$); + this._setTileSizeSubscription = this._container.renderService.size$ + .switchMap(function (size) { + return Observable_1.Observable + .combineLatest(textureProvider$, Observable_1.Observable.of(size)) + .first(); + }) + .subscribe(function (_a) { + var provider = _a[0], size = _a[1]; + var viewportSize = Math.max(size.width, size.height); + var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512; + provider.setTileSize(tileSize); + }); + this._abortTextureProviderSubscription = textureProvider$ + .pairwise() + .subscribe(function (pair) { + var previous = pair[0]; + previous.abort(); + }); + var roiTrigger$ = Observable_1.Observable + .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250)) + .map(function (_a) { + var camera = _a[0], size = _a[1]; + return [ + camera.camera.position.clone(), + camera.camera.lookat.clone(), + camera.zoom.valueOf(), + size.height.valueOf(), + size.width.valueOf() + ]; + }) + .pairwise() + .skipWhile(function (pls) { + return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0; + }) + .map(function (pls) { + var samePosition = pls[0][0].equals(pls[1][0]); + var sameLookat = pls[0][1].equals(pls[1][1]); + var sameZoom = pls[0][2] === pls[1][2]; + var sameHeight = pls[0][3] === pls[1][3]; + var sameWidth = pls[0][4] === pls[1][4]; + return samePosition && sameLookat && sameZoom && sameHeight && sameWidth; + }) + .distinctUntilChanged() + .filter(function (stalled) { + return stalled; + }) + .switchMap(function (stalled) { + return _this._container.renderService.renderCameraFrame$ + .first(); + }) + .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$); + this._setRegionOfInterestSubscription = textureProvider$ + .switchMap(function (provider) { + return roiTrigger$ + .map(function (_a) { + var camera = _a[0], size = _a[1], transform = _a[2]; + return [ + _this._roiCalculator.computeRegionOfInterest(camera, size, transform), + provider, + ]; + }); + }) + .filter(function (args) { + return !args[1].disposed; }) .subscribe(function (args) { - var event = args[0]; - var render = args[1]; - var transform = args[2]; - var element = _this._container.element; - var offsetWidth = element.offsetWidth; - var offsetHeight = element.offsetHeight; - var clientRect = element.getBoundingClientRect(); - var canvasX = event.clientX - clientRect.left; - var canvasY = event.clientY - clientRect.top; - var unprojected = _this._unproject(canvasX, canvasY, offsetWidth, offsetHeight, render.perspective); - var reference = transform.projectBasic(unprojected.toArray()); - var deltaY = event.deltaY; - if (event.deltaMode === 1) { - deltaY = 40 * deltaY; - } - else if (event.deltaMode === 2) { - deltaY = 800 * deltaY; - } - var zoom = -3 * deltaY / offsetHeight; - _this._navigator.stateService.zoomIn(zoom, reference); + var roi = args[0]; + var provider = args[1]; + provider.setRegionOfInterest(roi); }); - this._pinchSubscription = this._container.touchService.pinch$ - .withLatestFrom(this._navigator.stateService.currentState$, function (p, f) { - return [p, f]; + var hasTexture$ = textureProvider$ + .switchMap(function (provider) { + return provider.hasTexture$; + }) + .startWith(false) + .publishReplay(1) + .refCount(); + this._hasTextureSubscription = hasTexture$.subscribe(function () { }); + var nodeImage$ = this._navigator.stateService.currentState$ + .filter(function (frame) { + return frame.state.nodesAhead === 0; + }) + .map(function (frame) { + return frame.state.currentNode; + }) + .distinctUntilChanged(undefined, function (node) { + return node.key; }) + .debounceTime(1000) + .withLatestFrom(hasTexture$) .filter(function (args) { - var state = args[1].state; - return state.currentNode.fullPano || state.nodesAhead < 1; + return !args[1]; }) .map(function (args) { return args[0]; }) - .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (p, r, t) { - return [p, r, t]; + .filter(function (node) { + return node.pano ? + Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize : + Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize; + }) + .switchMap(function (node) { + var baseImageSize = node.pano ? + Utils_1.Settings.basePanoramaSize : + Utils_1.Settings.baseImageSize; + if (Math.max(node.image.width, node.image.height) > baseImageSize) { + return Observable_1.Observable.empty(); + } + var image$ = node + .cacheImage$(Utils_1.Settings.maxImageSize) + .map(function (n) { + return [n.image, n]; + }); + return image$ + .takeUntil(hasTexture$ + .filter(function (hasTexture) { + return hasTexture; + })) + .catch(function (error, caught) { + console.error("Failed to fetch high res image (" + node.key + ")", error); + return Observable_1.Observable.empty(); + }); }) + .publish() + .refCount(); + this._updateBackgroundSubscription = nodeImage$ + .withLatestFrom(textureProvider$) .subscribe(function (args) { - var pinch = args[0]; - var render = args[1]; - var transform = args[2]; - var element = _this._container.element; - var offsetWidth = element.offsetWidth; - var offsetHeight = element.offsetHeight; - var clientRect = element.getBoundingClientRect(); - var unprojected = _this._unproject(pinch.centerClientX - clientRect.left, pinch.centerClientY - clientRect.top, offsetWidth, offsetHeight, render.perspective); - var reference = transform.projectBasic(unprojected.toArray()); - var zoom = 3 * pinch.distanceChange / Math.min(offsetHeight, offsetWidth); - _this._navigator.stateService.zoomIn(zoom, reference); + if (args[0][1].key !== args[1].key || + args[1].disposed) { + return; + } + args[1].updateBackground(args[0][0]); }); - this._container.mouseService.claimMouse(this._name, 0); - }; - MouseComponent.prototype._deactivate = function () { - this._container.mouseService.unclaimMouse(this._name); - this._activeSubscription.unsubscribe(); - this._cursorSubscription.unsubscribe(); - this._movementSubscription.unsubscribe(); - this._mouseWheelSubscription.unsubscribe(); - this._pinchSubscription.unsubscribe(); + this._updateTextureImageSubscription = nodeImage$ + .map(function (imn) { + return function (renderer) { + renderer.updateTextureImage(imn[0], imn[1]); + return renderer; + }; + }) + .subscribe(this._rendererOperation$); }; - MouseComponent.prototype._getDefaultConfiguration = function () { - return {}; + ImagePlaneComponent.prototype._deactivate = function () { + this._rendererDisposer$.next(null); + this._abortTextureProviderSubscription.unsubscribe(); + this._hasTextureSubscription.unsubscribe(); + this._rendererSubscription.unsubscribe(); + this._setRegionOfInterestSubscription.unsubscribe(); + this._setTextureProviderSubscription.unsubscribe(); + this._setTileSizeSubscription.unsubscribe(); + this._stateSubscription.unsubscribe(); + this._textureProviderSubscription.unsubscribe(); + this._updateBackgroundSubscription.unsubscribe(); + this._updateTextureImageSubscription.unsubscribe(); }; - MouseComponent.prototype._unproject = function (canvasX, canvasY, offsetWidth, offsetHeight, perspectiveCamera) { - var projectedX = 2 * canvasX / offsetWidth - 1; - var projectedY = 1 - 2 * canvasY / offsetHeight; - return new THREE.Vector3(projectedX, projectedY, 1).unproject(perspectiveCamera); + ImagePlaneComponent.prototype._getDefaultConfiguration = function () { + return { imageTiling: false }; }; - /** @inheritdoc */ - MouseComponent.componentName = "mouse"; - return MouseComponent; + ImagePlaneComponent.componentName = "imagePlane"; + return ImagePlaneComponent; }(Component_1.Component)); -exports.MouseComponent = MouseComponent; -Component_1.ComponentService.register(MouseComponent); +exports.ImagePlaneComponent = ImagePlaneComponent; +Component_1.ComponentService.register(ImagePlaneComponent); +exports.default = ImagePlaneComponent; + +},{"../../Component":290,"../../Render":296,"../../Tiles":299,"../../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34}],321:[function(require,module,exports){ +"use strict"; +/// Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = MouseComponent; +var Component_1 = require("../../Component"); +var ImagePlaneGLRenderer = /** @class */ (function () { + function ImagePlaneGLRenderer() { + this._factory = new Component_1.MeshFactory(); + this._scene = new Component_1.MeshScene(); + this._alpha = 0; + this._alphaOld = 0; + this._fadeOutSpeed = 0.05; + this._currentKey = null; + this._previousKey = null; + this._providerDisposers = {}; + this._frameId = 0; + this._needsRender = false; + } + Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", { + get: function () { + return this._frameId; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", { + get: function () { + return this._needsRender; + }, + enumerable: true, + configurable: true + }); + ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () { + this._needsRender = true; + }; + ImagePlaneGLRenderer.prototype.updateFrame = function (frame) { + this._updateFrameId(frame.id); + this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender; + this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender; + this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender; + }; + ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) { + var _this = this; + if (key !== this._currentKey) { + return; + } + var createdSubscription = provider.textureCreated$ + .subscribe(function (texture) { + _this._updateTexture(texture); + }); + var updatedSubscription = provider.textureUpdated$ + .subscribe(function (updated) { + _this._needsRender = true; + }); + var dispose = function () { + createdSubscription.unsubscribe(); + updatedSubscription.unsubscribe(); + provider.dispose(); + }; + if (key in this._providerDisposers) { + var disposeProvider = this._providerDisposers[key]; + disposeProvider(); + delete this._providerDisposers[key]; + } + this._providerDisposers[key] = dispose; + }; + ImagePlaneGLRenderer.prototype._updateTexture = function (texture) { + this._needsRender = true; + for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) { + var plane = _a[_i]; + var material = plane.material; + var oldTexture = material.uniforms.projectorTex.value; + material.uniforms.projectorTex.value = null; + oldTexture.dispose(); + material.uniforms.projectorTex.value = texture; + } + }; + ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) { + if (this._currentKey !== node.key) { + return; + } + this._needsRender = true; + for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) { + var plane = _a[_i]; + var material = plane.material; + var texture = material.uniforms.projectorTex.value; + texture.image = image; + texture.needsUpdate = true; + } + }; + ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) { + var planeAlpha = this._scene.imagePlanesOld.length ? 1 : this._alpha; + for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) { + var plane = _a[_i]; + plane.material.uniforms.opacity.value = planeAlpha; + } + for (var _b = 0, _c = this._scene.imagePlanesOld; _b < _c.length; _b++) { + var plane = _c[_b]; + plane.material.uniforms.opacity.value = this._alphaOld; + } + renderer.render(this._scene.scene, perspectiveCamera); + renderer.render(this._scene.sceneOld, perspectiveCamera); + for (var _d = 0, _e = this._scene.imagePlanes; _d < _e.length; _d++) { + var plane = _e[_d]; + plane.material.uniforms.opacity.value = this._alpha; + } + renderer.render(this._scene.scene, perspectiveCamera); + }; + ImagePlaneGLRenderer.prototype.clearNeedsRender = function () { + this._needsRender = false; + }; + ImagePlaneGLRenderer.prototype.dispose = function () { + this._scene.clear(); + }; + ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) { + this._frameId = frameId; + }; + ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) { + if (alpha === this._alpha) { + return false; + } + this._alpha = alpha; + return true; + }; + ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) { + if (alpha < 1 || this._alphaOld === 0) { + return false; + } + this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed); + return true; + }; + ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) { + if (state.currentNode == null || state.currentNode.key === this._currentKey) { + return false; + } + var previousKey = state.previousNode != null ? state.previousNode.key : null; + var currentKey = state.currentNode.key; + if (this._previousKey !== previousKey && + this._previousKey !== currentKey && + this._previousKey in this._providerDisposers) { + var disposeProvider = this._providerDisposers[this._previousKey]; + disposeProvider(); + delete this._providerDisposers[this._previousKey]; + } + if (previousKey != null) { + if (previousKey !== this._currentKey && previousKey !== this._previousKey) { + var previousMesh = this._factory.createMesh(state.previousNode, state.previousTransform); + this._scene.updateImagePlanes([previousMesh]); + } + this._previousKey = previousKey; + } + this._currentKey = currentKey; + var currentMesh = this._factory.createMesh(state.currentNode, state.currentTransform); + this._scene.updateImagePlanes([currentMesh]); + this._alphaOld = 1; + return true; + }; + return ImagePlaneGLRenderer; +}()); +exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer; +exports.default = ImagePlaneGLRenderer; -},{"../Component":207,"../Geo":210,"rxjs/Observable":28,"rxjs/add/observable/merge":43,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/withLatestFrom":76,"three":157,"virtual-dom":163}],230:[function(require,module,exports){ -/// +},{"../../Component":290}],322:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); -var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/first"); -var Edge_1 = require("../Edge"); -var Component_1 = require("../Component"); -var NavigationComponent = (function (_super) { - __extends(NavigationComponent, _super); - function NavigationComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._dirNames = {}; - this._dirNames[Edge_1.EdgeDirection.StepForward] = "Forward"; - this._dirNames[Edge_1.EdgeDirection.StepBackward] = "Backward"; - this._dirNames[Edge_1.EdgeDirection.StepLeft] = "Left"; - this._dirNames[Edge_1.EdgeDirection.StepRight] = "Right"; - this._dirNames[Edge_1.EdgeDirection.TurnLeft] = "Turnleft"; - this._dirNames[Edge_1.EdgeDirection.TurnRight] = "Turnright"; - this._dirNames[Edge_1.EdgeDirection.TurnU] = "Turnaround"; +Object.defineProperty(exports, "__esModule", { value: true }); +var CoverState; +(function (CoverState) { + CoverState[CoverState["Hidden"] = 0] = "Hidden"; + CoverState[CoverState["Loading"] = 1] = "Loading"; + CoverState[CoverState["Visible"] = 2] = "Visible"; +})(CoverState = exports.CoverState || (exports.CoverState = {})); + +},{}],323:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Enumeration for slider mode. + * + * @enum {number} + * @readonly + * + * @description Modes for specifying how transitions + * between nodes are performed in slider mode. Only + * applicable when the slider component determines + * that transitions with motion is possilble. When it + * is not, the stationary mode will be applied. + */ +var SliderMode; +(function (SliderMode) { + /** + * Transitions with motion. + * + * @description The slider component moves the + * camera between the node origins. + * + * In this mode it is not possible to zoom or pan. + * + * The slider component falls back to stationary + * mode when it determines that the pair of nodes + * does not have a strong enough relation. + */ + SliderMode[SliderMode["Motion"] = 0] = "Motion"; + /** + * Stationary transitions. + * + * @description The camera is stationary. + * + * In this mode it is possible to zoom and pan. + */ + SliderMode[SliderMode["Stationary"] = 1] = "Stationary"; +})(SliderMode = exports.SliderMode || (exports.SliderMode = {})); + +},{}],324:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ICoverConfiguration_1 = require("./ICoverConfiguration"); +exports.CoverState = ICoverConfiguration_1.CoverState; +var ISliderConfiguration_1 = require("./ISliderConfiguration"); +exports.SliderMode = ISliderConfiguration_1.SliderMode; + +},{"./ICoverConfiguration":322,"./ISliderConfiguration":323}],325:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../Component"); +var Edge_1 = require("../../Edge"); +/** + * The `KeyPlayHandler` allows the user to control the play behavior + * using the following key commands: + * + * `Spacebar`: Start or stop playing. + * `SHIFT` + `D`: Switch direction. + * `<`: Decrease speed. + * `>`: Increase speed. + * + * @example + * ``` + * var keyboardComponent = viewer.getComponent("keyboard"); + * + * keyboardComponent.keyPlay.disable(); + * keyboardComponent.keyPlay.enable(); + * + * var isEnabled = keyboardComponent.keyPlay.isEnabled; + * ``` + */ +var KeyPlayHandler = /** @class */ (function (_super) { + __extends(KeyPlayHandler, _super); + function KeyPlayHandler() { + return _super !== null && _super.apply(this, arguments) || this; } - NavigationComponent.prototype._activate = function () { + KeyPlayHandler.prototype._enable = function () { var _this = this; - this._renderSubscription = this._navigator.stateService.currentNode$ + this._keyDownSubscription = this._container.keyboardService.keyDown$ + .withLatestFrom(this._navigator.playService.playing$, this._navigator.playService.direction$, this._navigator.playService.speed$, this._navigator.stateService.currentNode$ .switchMap(function (node) { - return node.pano ? - Observable_1.Observable.of([]) : - Observable_1.Observable.combineLatest(node.sequenceEdges$, node.spatialEdges$, function (seq, spa) { - return seq.edges.concat(spa.edges); - }); - }) - .map(function (edges) { - var btns = []; - for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) { - var edge = edges_1[_i]; - var direction = edge.data.direction; - var name_1 = _this._dirNames[direction]; - if (name_1 == null) { - continue; - } - btns.push(_this._createVNode(direction, name_1)); + return node.sequenceEdges$; + })) + .subscribe(function (_a) { + var event = _a[0], playing = _a[1], direction = _a[2], speed = _a[3], status = _a[4]; + if (event.altKey || event.ctrlKey || event.metaKey) { + return; } - return { name: _this._name, vnode: vd.h("div.NavigationComponent", btns) }; - }) - .subscribe(this._container.domRenderer.render$); - }; - NavigationComponent.prototype._deactivate = function () { - this._renderSubscription.unsubscribe(); + switch (event.key) { + case "D": + if (!event.shiftKey) { + return; + } + var newDirection = playing ? + null : direction === Edge_1.EdgeDirection.Next ? + Edge_1.EdgeDirection.Prev : direction === Edge_1.EdgeDirection.Prev ? + Edge_1.EdgeDirection.Next : null; + if (newDirection != null) { + _this._navigator.playService.setDirection(newDirection); + } + break; + case " ": + if (event.shiftKey) { + return; + } + if (playing) { + _this._navigator.playService.stop(); + } + else { + for (var _i = 0, _b = status.edges; _i < _b.length; _i++) { + var edge = _b[_i]; + if (edge.data.direction === direction) { + _this._navigator.playService.play(); + } + } + } + break; + case "<": + _this._navigator.playService.setSpeed(speed - 0.05); + break; + case ">": + _this._navigator.playService.setSpeed(speed + 0.05); + break; + default: + return; + } + event.preventDefault(); + }); }; - NavigationComponent.prototype._getDefaultConfiguration = function () { - return {}; + KeyPlayHandler.prototype._disable = function () { + this._keyDownSubscription.unsubscribe(); }; - NavigationComponent.prototype._createVNode = function (direction, name) { - var _this = this; - return vd.h("span.Direction.Direction" + name, { - onclick: function (ev) { - _this._navigator.moveDir$(direction) - .subscribe(function (node) { return; }, function (error) { console.error(error); }); - }, - }, []); + KeyPlayHandler.prototype._getConfiguration = function (enable) { + return { keyZoom: enable }; }; - NavigationComponent.componentName = "navigation"; - return NavigationComponent; -}(Component_1.Component)); -exports.NavigationComponent = NavigationComponent; -Component_1.ComponentService.register(NavigationComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = NavigationComponent; + return KeyPlayHandler; +}(Component_1.HandlerBase)); +exports.KeyPlayHandler = KeyPlayHandler; +exports.default = KeyPlayHandler; -},{"../Component":207,"../Edge":208,"rxjs/Observable":28,"rxjs/add/operator/first":58,"rxjs/add/operator/map":60,"virtual-dom":163}],231:[function(require,module,exports){ -/// +},{"../../Component":290,"../../Edge":291}],326:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var _ = require("underscore"); -var vd = require("virtual-dom"); -var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/observable/fromPromise"); -require("rxjs/add/observable/of"); -require("rxjs/add/operator/combineLatest"); -require("rxjs/add/operator/distinct"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/mergeMap"); -require("rxjs/add/operator/pluck"); -require("rxjs/add/operator/scan"); -var Component_1 = require("../Component"); -var DescriptionState = (function () { - function DescriptionState() { - } - return DescriptionState; -}()); -var RouteState = (function () { - function RouteState() { - } - return RouteState; -}()); -var RouteTrack = (function () { - function RouteTrack() { - this.nodeInstructions = []; - this.nodeInstructionsOrdered = []; - } - return RouteTrack; -}()); -var RouteComponent = (function (_super) { - __extends(RouteComponent, _super); - function RouteComponent(name, container, navigator) { - _super.call(this, name, container, navigator); +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../Component"); +var Edge_1 = require("../../Edge"); +var Error_1 = require("../../Error"); +/** + * The `KeySequenceNavigationHandler` allows the user to navigate through a sequence using the + * following key commands: + * + * `ALT` + `Up Arrow`: Navigate to next image in the sequence. + * `ALT` + `Down Arrow`: Navigate to previous image in sequence. + * + * @example + * ``` + * var keyboardComponent = viewer.getComponent("keyboard"); + * + * keyboardComponent.keySequenceNavigation.disable(); + * keyboardComponent.keySequenceNavigation.enable(); + * + * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled; + * ``` + */ +var KeySequenceNavigationHandler = /** @class */ (function (_super) { + __extends(KeySequenceNavigationHandler, _super); + function KeySequenceNavigationHandler() { + return _super !== null && _super.apply(this, arguments) || this; } - RouteComponent.prototype._activate = function () { + KeySequenceNavigationHandler.prototype._enable = function () { var _this = this; - var _slowedStream$; - _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) { - return (frame.id % 2) === 0; - }).filter(function (frame) { - return frame.state.nodesAhead < 15; - }).distinctUntilChanged(undefined, function (frame) { - return frame.state.lastNode.key; + var sequenceEdges$ = this._navigator.stateService.currentNode$ + .switchMap(function (node) { + return node.sequenceEdges$; }); - var _routeTrack$; - _routeTrack$ = this.configuration$.mergeMap(function (conf) { - return Observable_1.Observable.from(conf.paths); - }).distinct(function (p1, p2) { - return p1.sequenceKey === p2.sequenceKey; - }).mergeMap(function (path) { - return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey]) - .map(function (sequenceByKey) { - return sequenceByKey[path.sequenceKey]; - }); - }).combineLatest(this.configuration$, function (sequence, conf) { - var i = 0; - var instructionPlaces = []; - for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) { - var path = _a[_i]; - if (path.sequenceKey === sequence.key) { - var nodeInstructions = []; - var saveKey = false; - for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) { - var key = _c[_b]; - if (path.startKey === key) { - saveKey = true; - } - if (saveKey) { - var description = null; - for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) { - var infoKey = _e[_d]; - if (infoKey.key === key) { - description = infoKey.description; - } - } - nodeInstructions.push({ description: description, key: key }); - } - if (path.stopKey === key) { - saveKey = false; - } - } - instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i }); - } - i++; - } - return instructionPlaces; - }).scan(function (routeTrack, instructionPlaces) { - for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) { - var instructionPlace = instructionPlaces_1[_i]; - routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions; - } - routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered); - return routeTrack; - }, new RouteTrack()); - this._disposable = _slowedStream$ - .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) { - return { conf: conf, frame: frame, routeTrack: routeTrack }; - }).scan(function (routeState, rtAndFrame) { - if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) { - routeState.routeTrack = rtAndFrame.routeTrack; - routeState.currentNode = rtAndFrame.frame.state.currentNode; - routeState.lastNode = rtAndFrame.frame.state.lastNode; - routeState.playing = true; - } - else { - _this._navigator.stateService.cutNodes(); - routeState.playing = false; - } - return routeState; - }, new RouteState()) - .filter(function (routeState) { - return routeState.playing; - }).filter(function (routeState) { - for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) { - var nodeInstruction = _a[_i]; - if (!nodeInstruction) { - continue; - } - if (nodeInstruction.key === routeState.lastNode.key) { - return true; - } - } - return false; - }).distinctUntilChanged(undefined, function (routeState) { - return routeState.lastNode.key; - }).mergeMap(function (routeState) { - var i = 0; - for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) { - var nodeInstruction = _a[_i]; - if (nodeInstruction.key === routeState.lastNode.key) { + this._keyDownSubscription = this._container.keyboardService.keyDown$ + .withLatestFrom(sequenceEdges$) + .subscribe(function (_a) { + var event = _a[0], edgeStatus = _a[1]; + var direction = null; + switch (event.keyCode) { + case 38:// up + direction = Edge_1.EdgeDirection.Next; break; - } - i++; + case 40:// down + direction = Edge_1.EdgeDirection.Prev; + break; + default: + return; } - var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1]; - if (!nextInstruction) { - return Observable_1.Observable.of(null); + event.preventDefault(); + if (!event.altKey || event.shiftKey || !edgeStatus.cached) { + return; } - return _this._navigator.graphService.cacheNode$(nextInstruction.key); - }).combineLatest(this.configuration$, function (node, conf) { - return { conf: conf, node: node }; - }).filter(function (cAN) { - return cAN.node !== null && cAN.conf.playing; - }).pluck("node").subscribe(this._navigator.stateService.appendNode$); - this._disposableDescription = this._navigator.stateService.currentNode$ - .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) { - if (conf.playing !== undefined && !conf.playing) { - return "quit"; + for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) { + var edge = _b[_i]; + if (edge.data.direction === direction) { + _this._navigator.moveToKey$(edge.to) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); + } + }); + return; + } } - var description = null; - for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) { - var nodeInstruction = _a[_i]; - if (nodeInstruction.key === node.key) { - description = nodeInstruction.description; + }); + }; + KeySequenceNavigationHandler.prototype._disable = function () { + this._keyDownSubscription.unsubscribe(); + }; + KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) { + return { keySequenceNavigation: enable }; + }; + return KeySequenceNavigationHandler; +}(Component_1.HandlerBase)); +exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler; +exports.default = KeySequenceNavigationHandler; + +},{"../../Component":290,"../../Edge":291,"../../Error":292}],327:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../Component"); +var Edge_1 = require("../../Edge"); +var Error_1 = require("../../Error"); +/** + * The `KeySpatialNavigationHandler` allows the user to navigate through a sequence using the + * following key commands: + * + * `Up Arrow`: Step forward. + * `Down Arrow`: Step backward. + * `Left Arrow`: Step to the left. + * `Rigth Arrow`: Step to the right. + * `SHIFT` + `Down Arrow`: Turn around. + * `SHIFT` + `Left Arrow`: Turn to the left. + * `SHIFT` + `Rigth Arrow`: Turn to the right. + * + * @example + * ``` + * var keyboardComponent = viewer.getComponent("keyboard"); + * + * keyboardComponent.keySpatialNavigation.disable(); + * keyboardComponent.keySpatialNavigation.enable(); + * + * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled; + * ``` + */ +var KeySpatialNavigationHandler = /** @class */ (function (_super) { + __extends(KeySpatialNavigationHandler, _super); + function KeySpatialNavigationHandler(component, container, navigator, spatial) { + var _this = _super.call(this, component, container, navigator) || this; + _this._spatial = spatial; + return _this; + } + KeySpatialNavigationHandler.prototype._enable = function () { + var _this = this; + var spatialEdges$ = this._navigator.stateService.currentNode$ + .switchMap(function (node) { + return node.spatialEdges$; + }); + this._keyDownSubscription = this._container.keyboardService.keyDown$ + .withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$) + .subscribe(function (_a) { + var event = _a[0], edgeStatus = _a[1], frame = _a[2]; + var pano = frame.state.currentNode.pano; + var direction = null; + switch (event.keyCode) { + case 37:// left + direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft; break; - } - } - return description; - }).scan(function (descriptionState, description) { - if (description !== descriptionState.description && description !== null) { - descriptionState.description = description; - descriptionState.showsLeft = 6; - } - else { - descriptionState.showsLeft--; + case 38:// up + direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward; + break; + case 39:// right + direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight; + break; + case 40:// down + direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward; + break; + default: + return; } - if (description === "quit") { - descriptionState.description = null; + event.preventDefault(); + if (event.altKey || !edgeStatus.cached || + (event.shiftKey && pano)) { + return; } - return descriptionState; - }, new DescriptionState()).map(function (descriptionState) { - if (descriptionState.showsLeft > 0 && descriptionState.description) { - return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) }; + if (!pano) { + _this._moveDir(direction, edgeStatus); } else { - return { name: _this._name, vnode: vd.h("div", []) }; + var shifts = {}; + shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI; + shifts[Edge_1.EdgeDirection.StepForward] = 0; + shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2; + shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2; + var phi = _this._rotationFromCamera(frame.state.camera).phi; + var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]); + var threshold = Math.PI / 4; + var edges = edgeStatus.edges.filter(function (e) { + return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction; + }); + var smallestAngle = Number.MAX_VALUE; + var toKey = null; + for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) { + var edge = edges_1[_i]; + var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle)); + if (angle < Math.min(smallestAngle, threshold)) { + smallestAngle = angle; + toKey = edge.to; + } + } + if (toKey == null) { + return; + } + _this._moveToKey(toKey); } - }).subscribe(this._container.domRenderer.render$); + }); }; - RouteComponent.prototype._deactivate = function () { - this._disposable.unsubscribe(); - this._disposableDescription.unsubscribe(); + KeySpatialNavigationHandler.prototype._disable = function () { + this._keyDownSubscription.unsubscribe(); }; - RouteComponent.prototype._getDefaultConfiguration = function () { - return {}; + KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) { + return { keySpatialNavigation: enable }; }; - RouteComponent.prototype.play = function () { - this.configure({ playing: true }); + KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) { + for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { + var edge = _a[_i]; + if (edge.data.direction === direction) { + this._moveToKey(edge.to); + return; + } + } }; - RouteComponent.prototype.stop = function () { - this.configure({ playing: false }); + KeySpatialNavigationHandler.prototype._moveToKey = function (key) { + this._navigator.moveToKey$(key) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); + } + }); }; - RouteComponent.prototype._getRouteAnnotationNode = function (description) { - return vd.h("div.RouteFrame", {}, [ - vd.h("p", { textContent: description }, []), - ]); + KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) { + var direction = camera.lookat.clone().sub(camera.position); + var upProjection = direction.clone().dot(camera.up); + var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection)); + var phi = Math.atan2(planeProjection.y, planeProjection.x); + var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]); + return { phi: phi, theta: theta }; }; - RouteComponent.componentName = "route"; - return RouteComponent; -}(Component_1.Component)); -exports.RouteComponent = RouteComponent; -Component_1.ComponentService.register(RouteComponent); + return KeySpatialNavigationHandler; +}(Component_1.HandlerBase)); +exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler; +exports.default = KeySpatialNavigationHandler; + +},{"../../Component":290,"../../Edge":291,"../../Error":292}],328:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = RouteComponent; +var Component_1 = require("../../Component"); +/** + * The `KeyZoomHandler` allows the user to zoom in and out using the + * following key commands: + * + * `+`: Zoom in. + * `-`: Zoom out. + * + * @example + * ``` + * var keyboardComponent = viewer.getComponent("keyboard"); + * + * keyboardComponent.keyZoom.disable(); + * keyboardComponent.keyZoom.enable(); + * + * var isEnabled = keyboardComponent.keyZoom.isEnabled; + * ``` + */ +var KeyZoomHandler = /** @class */ (function (_super) { + __extends(KeyZoomHandler, _super); + function KeyZoomHandler(component, container, navigator, viewportCoords) { + var _this = _super.call(this, component, container, navigator) || this; + _this._viewportCoords = viewportCoords; + return _this; + } + KeyZoomHandler.prototype._enable = function () { + var _this = this; + this._keyDownSubscription = this._container.keyboardService.keyDown$ + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .subscribe(function (_a) { + var event = _a[0], render = _a[1], transform = _a[2]; + if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) { + return; + } + var delta = 0; + switch (event.key) { + case "+": + delta = 1; + break; + case "-": + delta = -1; + break; + default: + return; + } + event.preventDefault(); + var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective); + var reference = transform.projectBasic(unprojected.toArray()); + _this._navigator.stateService.zoomIn(delta, reference); + }); + }; + KeyZoomHandler.prototype._disable = function () { + this._keyDownSubscription.unsubscribe(); + }; + KeyZoomHandler.prototype._getConfiguration = function (enable) { + return { keyZoom: enable }; + }; + return KeyZoomHandler; +}(Component_1.HandlerBase)); +exports.KeyZoomHandler = KeyZoomHandler; +exports.default = KeyZoomHandler; -},{"../Component":207,"rxjs/Observable":28,"rxjs/add/observable/fromPromise":42,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":49,"rxjs/add/operator/distinct":52,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/mergeMap":63,"rxjs/add/operator/pluck":65,"rxjs/add/operator/scan":68,"underscore":158,"virtual-dom":163}],232:[function(require,module,exports){ +},{"../../Component":290}],329:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/operator/buffer"); -require("rxjs/add/operator/debounceTime"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/scan"); -var Component_1 = require("../Component"); -var StatsComponent = (function (_super) { - __extends(StatsComponent, _super); - function StatsComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - } - StatsComponent.prototype._activate = function () { +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../Component"); +var Geo_1 = require("../../Geo"); +/** + * @class KeyboardComponent + * + * @classdesc Component for keyboard event handling. + * + * To retrive and use the keyboard component + * + * @example + * ``` + * var viewer = new Mapillary.Viewer( + * "", + * "", + * ""); + * + * var keyboardComponent = viewer.getComponent("keyboard"); + * ``` + */ +var KeyboardComponent = /** @class */ (function (_super) { + __extends(KeyboardComponent, _super); + function KeyboardComponent(name, container, navigator) { + var _this = _super.call(this, name, container, navigator) || this; + _this._keyPlayHandler = new Component_1.KeyPlayHandler(_this, container, navigator); + _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator); + _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial()); + _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords()); + return _this; + } + Object.defineProperty(KeyboardComponent.prototype, "keyPlay", { + /** + * Get key play. + * + * @returns {KeyPlayHandler} The key play handler. + */ + get: function () { + return this._keyPlayHandler; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", { + /** + * Get key sequence navigation. + * + * @returns {KeySequenceNavigationHandler} The key sequence navigation handler. + */ + get: function () { + return this._keySequenceNavigationHandler; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", { + /** + * Get spatial. + * + * @returns {KeySpatialNavigationHandler} The spatial handler. + */ + get: function () { + return this._keySpatialNavigationHandler; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(KeyboardComponent.prototype, "keyZoom", { + /** + * Get key zoom. + * + * @returns {KeyZoomHandler} The key zoom handler. + */ + get: function () { + return this._keyZoomHandler; + }, + enumerable: true, + configurable: true + }); + KeyboardComponent.prototype._activate = function () { var _this = this; - this._sequenceSubscription = this._navigator.stateService.currentNode$ - .scan(function (keys, node) { - var sKey = node.sequenceKey; - keys.report = []; - if (!(sKey in keys.reported)) { - keys.report = [sKey]; - keys.reported[sKey] = true; + this._configurationSubscription = this._configuration$ + .subscribe(function (configuration) { + if (configuration.keyPlay) { + _this._keyPlayHandler.enable(); } - return keys; - }, { report: [], reported: {} }) - .filter(function (keys) { - return keys.report.length > 0; - }) - .mergeMap(function (keys) { - return _this._navigator.apiV3.sequenceViewAdd$(keys.report) - .catch(function (error, caught) { - console.error("Failed to report sequence stats (" + keys.report + ")", error); - return Observable_1.Observable.empty(); - }); - }) - .subscribe(); - this._imageSubscription = this._navigator.stateService.currentNode$ - .map(function (node) { - return node.key; - }) - .buffer(this._navigator.stateService.currentNode$.debounceTime(5000)) - .scan(function (keys, newKeys) { - keys.report = []; - for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) { - var key = newKeys_1[_i]; - if (!(key in keys.reported)) { - keys.report.push(key); - keys.reported[key] = true; - } + else { + _this._keyPlayHandler.disable(); } - return keys; - }, { report: [], reported: {} }) - .filter(function (keys) { - return keys.report.length > 0; - }) - .mergeMap(function (keys) { - return _this._navigator.apiV3.imageViewAdd$(keys.report) - .catch(function (error, caught) { - console.error("Failed to report image stats (" + keys.report + ")", error); - return Observable_1.Observable.empty(); - }); - }) - .subscribe(); + if (configuration.keySequenceNavigation) { + _this._keySequenceNavigationHandler.enable(); + } + else { + _this._keySequenceNavigationHandler.disable(); + } + if (configuration.keySpatialNavigation) { + _this._keySpatialNavigationHandler.enable(); + } + else { + _this._keySpatialNavigationHandler.disable(); + } + if (configuration.keyZoom) { + _this._keyZoomHandler.enable(); + } + else { + _this._keyZoomHandler.disable(); + } + }); }; - StatsComponent.prototype._deactivate = function () { - this._sequenceSubscription.unsubscribe(); - this._imageSubscription.unsubscribe(); + KeyboardComponent.prototype._deactivate = function () { + this._configurationSubscription.unsubscribe(); + this._keyPlayHandler.disable(); + this._keySequenceNavigationHandler.disable(); + this._keySpatialNavigationHandler.disable(); + this._keyZoomHandler.disable(); }; - StatsComponent.prototype._getDefaultConfiguration = function () { - return {}; + KeyboardComponent.prototype._getDefaultConfiguration = function () { + return { keyPlay: true, keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true }; }; - StatsComponent.componentName = "stats"; - return StatsComponent; + KeyboardComponent.componentName = "keyboard"; + return KeyboardComponent; }(Component_1.Component)); -exports.StatsComponent = StatsComponent; -Component_1.ComponentService.register(StatsComponent); +exports.KeyboardComponent = KeyboardComponent; +Component_1.ComponentService.register(KeyboardComponent); +exports.default = KeyboardComponent; + +},{"../../Component":290,"../../Geo":293}],330:[function(require,module,exports){ +"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = StatsComponent; +var MarkerComponent_1 = require("./MarkerComponent"); +exports.MarkerComponent = MarkerComponent_1.MarkerComponent; +var SimpleMarker_1 = require("./marker/SimpleMarker"); +exports.SimpleMarker = SimpleMarker_1.SimpleMarker; +var CircleMarker_1 = require("./marker/CircleMarker"); +exports.CircleMarker = CircleMarker_1.CircleMarker; -},{"../Component":207,"rxjs/Observable":28,"rxjs/add/operator/buffer":47,"rxjs/add/operator/debounceTime":51,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/scan":68}],233:[function(require,module,exports){ -/// +},{"./MarkerComponent":331,"./marker/CircleMarker":334,"./marker/SimpleMarker":336}],331:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var when = require("when"); var Observable_1 = require("rxjs/Observable"); -var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/operator/do"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/share"); var Component_1 = require("../../Component"); +var Render_1 = require("../../Render"); +var Graph_1 = require("../../Graph"); +var Geo_1 = require("../../Geo"); /** - * @class DirectionComponent - * @classdesc Component showing navigation arrows for steps and turns. + * @class MarkerComponent + * + * @classdesc Component for showing and editing 3D marker objects. + * + * The `add` method is used for adding new markers or replacing + * markers already in the set. + * + * If a marker already in the set has the same + * id as one of the markers added, the old marker will be removed and + * the added marker will take its place. + * + * It is not possible to update markers in the set by updating any properties + * directly on the marker object. Markers need to be replaced by + * re-adding them for updates to geographic position or configuration + * to be reflected. + * + * Markers added to the marker component can be either interactive + * or non-interactive. Different marker types define their behavior. + * Markers with interaction support can be configured with options + * to respond to dragging inside the viewer and be detected when + * retrieving markers from pixel points with the `getMarkerIdAt` method. + * + * To retrive and use the marker component + * + * @example + * ``` + * var viewer = new Mapillary.Viewer( + * "", + * "", + * "", + * { component: { marker: true } }); + * + * var markerComponent = viewer.getComponent("marker"); + * ``` */ -var DirectionComponent = (function (_super) { - __extends(DirectionComponent, _super); - function DirectionComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._renderer = new Component_1.DirectionDOMRenderer(this.defaultConfiguration, container.element); - this._hoveredKeySubject$ = new Subject_1.Subject(); - this._hoveredKey$ = this._hoveredKeySubject$.share(); +var MarkerComponent = /** @class */ (function (_super) { + __extends(MarkerComponent, _super); + function MarkerComponent(name, container, navigator) { + var _this = _super.call(this, name, container, navigator) || this; + _this._relativeGroundAltitude = -2; + _this._geoCoords = new Geo_1.GeoCoords(); + _this._graphCalculator = new Graph_1.GraphCalculator(); + _this._markerScene = new Component_1.MarkerScene(); + _this._markerSet = new Component_1.MarkerSet(); + _this._viewportCoords = new Geo_1.ViewportCoords(); + return _this; } - Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", { - /** - * Get hovered key observable. - * - * @description An observable emitting the key of the node for the direction - * arrow that is being hovered. When the mouse leaves a direction arrow null - * is emitted. - * - * @returns {Observable} - */ - get: function () { - return this._hoveredKey$; - }, - enumerable: true, - configurable: true - }); /** - * Set highlight key. + * Add markers to the marker set or replace markers in the marker set. * - * @description The arrow pointing towards the node corresponding to the - * highlight key will be highlighted. + * @description If a marker already in the set has the same + * id as one of the markers added, the old marker will be removed + * the added marker will take its place. * - * @param {string} highlightKey Key of node to be highlighted if existing - * among arrows. + * Any marker inside the visible bounding bbox + * will be initialized and placed in the viewer. + * + * @param {Array} markers - Markers to add. + * + * @example ```markerComponent.add([marker1, marker2]);``` */ - DirectionComponent.prototype.setHighlightKey = function (highlightKey) { - this.configure({ highlightKey: highlightKey }); + MarkerComponent.prototype.add = function (markers) { + this._markerSet.add(markers); }; /** - * Set min width of container element. + * Returns the marker in the marker set with the specified id, or + * undefined if the id matches no marker. * - * @description Set min width of the non transformed container element holding - * the navigation arrows. If the min width is larger than the max width the - * min width value will be used. + * @param {string} markerId - Id of the marker. * - * The container element is automatically resized when the resize - * method on the Viewer class is called. + * @example ```var marker = markerComponent.get("markerId");``` * - * @param {number} minWidth */ - DirectionComponent.prototype.setMinWidth = function (minWidth) { - this.configure({ minWidth: minWidth }); + MarkerComponent.prototype.get = function (markerId) { + return this._markerSet.get(markerId); }; /** - * Set max width of container element. + * Returns an array of all markers. * - * @description Set max width of the non transformed container element holding - * the navigation arrows. If the min width is larger than the max width the - * min width value will be used. + * @example ```var markers = markerComponent.getAll();``` + */ + MarkerComponent.prototype.getAll = function () { + return this._markerSet.getAll(); + }; + /** + * Returns the id of the interactive marker closest to the current camera + * position at the specified point. * - * The container element is automatically resized when the resize - * method on the Viewer class is called. + * @description Notice that the pixelPoint argument requires x, y + * coordinates from pixel space. * - * @param {number} minWidth + * With this function, you can use the coordinates provided by mouse + * events to get information out of the marker component. + * + * If no interactive geometry of an interactive marker exist at the pixel + * point, `null` will be returned. + * + * @param {Array} pixelPoint - Pixel coordinates on the viewer element. + * @returns {string} Id of the interactive marker closest to the camera. If no + * interactive marker exist at the pixel point, `null` will be returned. + * + * @example + * ``` + * markerComponent.getMarkerIdAt([100, 100]) + * .then((markerId) => { console.log(markerId); }); + * ``` */ - DirectionComponent.prototype.setMaxWidth = function (maxWidth) { - this.configure({ maxWidth: maxWidth }); + MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) { + var _this = this; + return when.promise(function (resolve, reject) { + _this._container.renderService.renderCamera$ + .first() + .map(function (render) { + var viewport = _this._viewportCoords + .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element); + var id = _this._markerScene.intersectObjects(viewport, render.perspective); + return id; + }) + .subscribe(function (id) { + resolve(id); + }, function (error) { + reject(error); + }); + }); }; - /** @inheritdoc */ - DirectionComponent.prototype.resize = function () { - this._renderer.resize(this._container.element); + /** + * Check if a marker exist in the marker set. + * + * @param {string} markerId - Id of the marker. + * + * @example ```var markerExists = markerComponent.has("markerId");``` + */ + MarkerComponent.prototype.has = function (markerId) { + return this._markerSet.has(markerId); }; - DirectionComponent.prototype._activate = function () { + /** + * Remove markers with the specified ids from the marker set. + * + * @param {Array} markerIds - Ids for markers to remove. + * + * @example ```markerComponent.remove(["id-1", "id-2"]);``` + */ + MarkerComponent.prototype.remove = function (markerIds) { + this._markerSet.remove(markerIds); + }; + /** + * Remove all markers from the marker set. + * + * @example ```markerComponent.removeAll();``` + */ + MarkerComponent.prototype.removeAll = function () { + this._markerSet.removeAll(); + }; + MarkerComponent.prototype._activate = function () { var _this = this; - this._configurationSubscription = this._configuration$ - .subscribe(function (configuration) { - _this._renderer.setConfiguration(configuration); - }); - this._nodeSubscription = this._navigator.stateService.currentNode$ - .do(function (node) { - _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) }); - _this._renderer.setNode(node); + var groundAltitude$ = this._navigator.stateService.currentState$ + .map(function (frame) { + return frame.state.camera.position.z + _this._relativeGroundAltitude; }) - .withLatestFrom(this._configuration$) - .switchMap(function (nc) { - var node = nc[0]; - var configuration = nc[1]; - return node.spatialEdges$ - .withLatestFrom(configuration.distinguishSequence ? - _this._navigator.graphService - .cacheSequence$(node.sequenceKey) - .catch(function (error, caught) { - console.error("Failed to cache sequence (" + node.sequenceKey + ")", error); - return Observable_1.Observable.empty(); - }) : - Observable_1.Observable.of(null)); + .distinctUntilChanged(function (a1, a2) { + return Math.abs(a1 - a2) < 0.01; }) - .subscribe(function (es) { - _this._renderer.setEdges(es[0], es[1]); + .publishReplay(1) + .refCount(); + var geoInitiated$ = Observable_1.Observable + .combineLatest(groundAltitude$, this._navigator.stateService.reference$) + .first() + .map(function () { }) + .publishReplay(1) + .refCount(); + var clampedConfiguration$ = this._configuration$ + .map(function (configuration) { + return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) }; }); - this._renderCameraSubscription = this._container.renderService.renderCameraFrame$ - .do(function (renderCamera) { - _this._renderer.setRenderCamera(renderCamera); - }) - .map(function (renderCamera) { - return _this._renderer; - }) - .filter(function (renderer) { - return renderer.needsRender; + var currentlatLon$ = this._navigator.stateService.currentNode$ + .map(function (node) { return node.latLon; }) + .publishReplay(1) + .refCount(); + var visibleBBox$ = Observable_1.Observable + .combineLatest(clampedConfiguration$, currentlatLon$) + .map(function (_a) { + var configuration = _a[0], latLon = _a[1]; + return _this._graphCalculator + .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2); }) - .map(function (renderer) { - return { name: _this._name, vnode: renderer.render(_this._navigator) }; + .publishReplay(1) + .refCount(); + var visibleMarkers$ = Observable_1.Observable + .combineLatest(Observable_1.Observable + .of(this._markerSet) + .concat(this._markerSet.changed$), visibleBBox$) + .map(function (_a) { + var set = _a[0], bbox = _a[1]; + return set.search(bbox); + }); + this._setChangedSubscription = geoInitiated$ + .switchMap(function () { + return visibleMarkers$ + .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$); }) - .subscribe(this._container.domRenderer.render$); - this._hoveredKeySubscription = Observable_1.Observable - .combineLatest([ - this._container.domRenderer.element$, - this._container.renderService.renderCamera$, - this._container.mouseService.mouseMove$.startWith(null), - this._container.mouseService.mouseUp$.startWith(null), - ], function (e, rc, mm, mu) { - return e; + .subscribe(function (_a) { + var markers = _a[0], reference = _a[1], alt = _a[2]; + var geoCoords = _this._geoCoords; + var markerScene = _this._markerScene; + var sceneMarkers = markerScene.markers; + var markersToRemove = Object.assign({}, sceneMarkers); + for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) { + var marker = markers_1[_i]; + if (marker.id in sceneMarkers) { + delete markersToRemove[marker.id]; + } + else { + var point3d = geoCoords + .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt); + markerScene.add(marker, point3d); + } + } + for (var id in markersToRemove) { + if (!markersToRemove.hasOwnProperty(id)) { + continue; + } + markerScene.remove(id); + } + }); + this._markersUpdatedSubscription = geoInitiated$ + .switchMap(function () { + return _this._markerSet.updated$ + .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$); }) - .map(function (element) { - var elements = element.getElementsByClassName("DirectionsPerspective"); - for (var i = 0; i < elements.length; i++) { - var hovered = elements.item(i).querySelector(":hover"); - if (hovered != null && hovered.hasAttribute("data-key")) { - return hovered.getAttribute("data-key"); + .subscribe(function (_a) { + var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3]; + var geoCoords = _this._geoCoords; + var markerScene = _this._markerScene; + for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) { + var marker = markers_2[_i]; + var exists = markerScene.has(marker.id); + var visible = marker.latLon.lat > sw.lat && + marker.latLon.lat < ne.lat && + marker.latLon.lon > sw.lon && + marker.latLon.lon < ne.lon; + if (visible) { + var point3d = geoCoords + .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt); + markerScene.add(marker, point3d); + } + else if (!visible && exists) { + markerScene.remove(marker.id); } } - return null; + }); + this._referenceSubscription = this._navigator.stateService.reference$ + .skip(1) + .withLatestFrom(groundAltitude$) + .subscribe(function (_a) { + var reference = _a[0], alt = _a[1]; + var geoCoords = _this._geoCoords; + var markerScene = _this._markerScene; + for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) { + var marker = _b[_i]; + var point3d = geoCoords + .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt); + markerScene.update(marker.id, point3d); + } + }); + this._adjustHeightSubscription = groundAltitude$ + .skip(1) + .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$) + .subscribe(function (_a) { + var alt = _a[0], reference = _a[1], latLon = _a[2]; + var geoCoords = _this._geoCoords; + var markerScene = _this._markerScene; + var position = geoCoords + .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt); + for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) { + var marker = _b[_i]; + var point3d = geoCoords + .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt); + var distanceX = point3d[0] - position[0]; + var distanceY = point3d[1] - position[1]; + var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY); + if (groundDistance > 50) { + continue; + } + markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50))); + } + }); + this._renderSubscription = this._navigator.stateService.currentState$ + .map(function (frame) { + var scene = _this._markerScene; + return { + name: _this._name, + render: { + frameId: frame.id, + needsRender: scene.needsRender, + render: scene.render.bind(scene), + stage: Render_1.GLRenderStage.Foreground, + }, + }; + }) + .subscribe(this._container.glRenderer.render$); + var hoveredMarkerId$ = Observable_1.Observable + .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$) + .map(function (_a) { + var render = _a[0], event = _a[1]; + var element = _this._container.element; + var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1]; + var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element); + var markerId = _this._markerScene.intersectObjects(viewport, render.perspective); + return markerId; + }) + .publishReplay(1) + .refCount(); + var draggingStarted$ = this._container.mouseService + .filtered$(this._name, this._container.mouseService.mouseDragStart$) + .map(function (event) { + return true; + }); + var draggingStopped$ = this._container.mouseService + .filtered$(this._name, this._container.mouseService.mouseDragEnd$) + .map(function (event) { + return false; + }); + var filteredDragging$ = Observable_1.Observable + .merge(draggingStarted$, draggingStopped$) + .startWith(false); + this._dragEventSubscription = draggingStarted$ + .withLatestFrom(hoveredMarkerId$) + .merge(Observable_1.Observable + .combineLatest(draggingStopped$, Observable_1.Observable.of(null))) + .startWith([false, null]) + .pairwise() + .subscribe(function (_a) { + var previous = _a[0], current = _a[1]; + var dragging = current[0]; + var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend; + var id = dragging ? current[1] : previous[1]; + var marker = _this._markerScene.get(id); + var markerEvent = { marker: marker, target: _this, type: eventType }; + _this.fire(eventType, markerEvent); + }); + var mouseDown$ = Observable_1.Observable + .merge(this._container.mouseService.mouseDown$ + .map(function (event) { return true; }), this._container.mouseService.documentMouseUp$ + .map(function (event) { return false; })) + .startWith(false); + this._mouseClaimSubscription = Observable_1.Observable + .combineLatest(this._container.mouseService.active$, hoveredMarkerId$.distinctUntilChanged(), mouseDown$, filteredDragging$) + .map(function (_a) { + var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3]; + return (!active && markerId != null && mouseDown) || filteredDragging; }) .distinctUntilChanged() - .subscribe(this._hoveredKeySubject$); + .subscribe(function (claim) { + if (claim) { + _this._container.mouseService.claimMouse(_this._name, 1); + _this._container.mouseService.claimWheel(_this._name, 1); + } + else { + _this._container.mouseService.unclaimMouse(_this._name); + _this._container.mouseService.unclaimWheel(_this._name); + } + }); + var offset$ = this._container.mouseService + .filtered$(this._name, this._container.mouseService.mouseDragStart$) + .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$) + .map(function (_a) { + var e = _a[0], id = _a[1], r = _a[2]; + var marker = _this._markerScene.get(id); + var element = _this._container.element; + var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1]; + var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1]; + var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY]; + return [marker, offset, r]; + }) + .publishReplay(1) + .refCount(); + this._updateMarkerSubscription = this._container.mouseService + .filtered$(this._name, this._container.mouseService.mouseDrag$) + .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$) + .subscribe(function (_a) { + var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3]; + if (!_this._markerScene.has(marker.id)) { + return; + } + var element = _this._container.element; + var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1]; + var groundX = canvasX - offset[0]; + var groundY = canvasY - offset[1]; + var _d = _this._viewportCoords + .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1]; + var direction = new THREE.Vector3(viewportX, viewportY, 1) + .unproject(render.perspective) + .sub(render.perspective.position) + .normalize(); + var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1); + if (distance < 0) { + return; + } + var intersection = direction + .clone() + .multiplyScalar(distance) + .add(render.perspective.position); + intersection.z = render.perspective.position.z + _this._relativeGroundAltitude; + var _e = _this._geoCoords + .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1]; + _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon }); + _this._markerSet.update(marker); + var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed }; + _this.fire(MarkerComponent.changed, markerEvent); + }); }; - DirectionComponent.prototype._deactivate = function () { - this._configurationSubscription.unsubscribe(); - this._nodeSubscription.unsubscribe(); - this._renderCameraSubscription.unsubscribe(); - this._hoveredKeySubscription.unsubscribe(); + MarkerComponent.prototype._deactivate = function () { + this._adjustHeightSubscription.unsubscribe(); + this._dragEventSubscription.unsubscribe(); + this._markersUpdatedSubscription.unsubscribe(); + this._mouseClaimSubscription.unsubscribe(); + this._referenceSubscription.unsubscribe(); + this._renderSubscription.unsubscribe(); + this._setChangedSubscription.unsubscribe(); + this._updateMarkerSubscription.unsubscribe(); + this._markerScene.clear(); }; - DirectionComponent.prototype._getDefaultConfiguration = function () { - return { - distinguishSequence: false, - maxWidth: 460, - minWidth: 260, - }; + MarkerComponent.prototype._getDefaultConfiguration = function () { + return { visibleBBoxSize: 100 }; }; - /** @inheritdoc */ - DirectionComponent.componentName = "direction"; - return DirectionComponent; + MarkerComponent.componentName = "marker"; + /** + * Fired when the position of a marker is changed. + * @event + * @type {IMarkerEvent} markerEvent - Marker event data. + * @example + * ``` + * markerComponent.on("changed", function(e) { + * console.log(e.marker.id, e.marker.latLon); + * }); + * ``` + */ + MarkerComponent.changed = "changed"; + /** + * Fired when a marker drag interaction starts. + * @event + * @type {IMarkerEvent} markerEvent - Marker event data. + * @example + * ``` + * markerComponent.on("dragstart", function(e) { + * console.log(e.marker.id, e.marker.latLon); + * }); + * ``` + */ + MarkerComponent.dragstart = "dragstart"; + /** + * Fired when a marker drag interaction ends. + * @event + * @type {IMarkerEvent} markerEvent - Marker event data. + * @example + * ``` + * markerComponent.on("dragend", function(e) { + * console.log(e.marker.id, e.marker.latLon); + * }); + * ``` + */ + MarkerComponent.dragend = "dragend"; + return MarkerComponent; }(Component_1.Component)); -exports.DirectionComponent = DirectionComponent; -Component_1.ComponentService.register(DirectionComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = DirectionComponent; +exports.MarkerComponent = MarkerComponent; +Component_1.ComponentService.register(MarkerComponent); +exports.default = MarkerComponent; -},{"../../Component":207,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/do":54,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/share":69,"virtual-dom":163}],234:[function(require,module,exports){ +},{"../../Component":290,"../../Geo":293,"../../Graph":294,"../../Render":296,"rxjs/Observable":29,"three":240,"when":287}],332:[function(require,module,exports){ "use strict"; -var Geo_1 = require("../../Geo"); -/** - * @class DirectionDOMCalculator - * @classdesc Helper class for calculating DOM CSS properties. - */ -var DirectionDOMCalculator = (function () { - function DirectionDOMCalculator(configuration, element) { - this._spatial = new Geo_1.Spatial(); - this._minThresholdWidth = 320; - this._maxThresholdWidth = 1480; - this._minThresholdHeight = 240; - this._maxThresholdHeight = 820; - this._configure(configuration); - this._resize(element); - this._reset(); +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var MarkerScene = /** @class */ (function () { + function MarkerScene(scene, raycaster) { + this._needsRender = false; + this._interactiveObjects = []; + this._markers = {}; + this._objectMarkers = {}; + this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster(); + this._scene = !!scene ? scene : new THREE.Scene(); } - Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", { - get: function () { - return this._minWidth; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", { - get: function () { - return this._maxWidth; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", { - get: function () { - return this._containerWidth; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", { - get: function () { - return this._containerWidthCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", { - get: function () { - return this._containerMarginCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", { - get: function () { - return this._containerLeftCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", { - get: function () { - return this._containerHeight; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", { - get: function () { - return this._containerHeightCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", { - get: function () { - return this._containerBottomCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", { - get: function () { - return this._stepCircleSize; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", { - get: function () { - return this._stepCircleSizeCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", { - get: function () { - return this._stepCircleMarginCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", { - get: function () { - return this._turnCircleSize; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", { - get: function () { - return this._turnCircleSizeCss; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", { - get: function () { - return this._outerRadius; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", { + Object.defineProperty(MarkerScene.prototype, "markers", { get: function () { - return this._innerRadius; + return this._markers; }, enumerable: true, configurable: true }); - Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", { + Object.defineProperty(MarkerScene.prototype, "needsRender", { get: function () { - return this._shadowOffset; + return this._needsRender; }, enumerable: true, configurable: true }); - /** - * Configures the min and max width values. - * - * @param {IDirectionConfiguration} configuration Configuration - * with min and max width values. - */ - DirectionDOMCalculator.prototype.configure = function (configuration) { - this._configure(configuration); - this._reset(); + MarkerScene.prototype.add = function (marker, position) { + if (marker.id in this._markers) { + this._dispose(marker.id); + } + marker.createGeometry(position); + this._scene.add(marker.geometry); + this._markers[marker.id] = marker; + for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) { + var interactiveObject = _a[_i]; + this._interactiveObjects.push(interactiveObject); + this._objectMarkers[interactiveObject.uuid] = marker.id; + } + this._needsRender = true; }; - /** - * Resizes all properties according to the width and height - * of the element. - * - * @param {HTMLElement} element The container element from which to extract - * the width and height. - */ - DirectionDOMCalculator.prototype.resize = function (element) { - this._resize(element); - this._reset(); + MarkerScene.prototype.clear = function () { + for (var id in this._markers) { + if (!this._markers.hasOwnProperty) { + continue; + } + this._dispose(id); + } + this._needsRender = true; }; - /** - * Calculates the coordinates on the unit circle for an angle. - * - * @param {number} angle Angle in radians. - * @returns {Array} The x and y coordinates on the unit circle. - */ - DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) { - return [Math.cos(angle), Math.sin(angle)]; + MarkerScene.prototype.get = function (id) { + return this._markers[id]; }; - /** - * Calculates the coordinates on the unit circle for the - * relative angle between the first and second angle. - * - * @param {number} first Angle in radians. - * @param {number} second Angle in radians. - * @returns {Array} The x and y coordinates on the unit circle - * for the relative angle between the first and second angle. - */ - DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) { - var relativeAngle = this._spatial.wrapAngle(first - second); - return this.angleToCoordinates(relativeAngle); + MarkerScene.prototype.getAll = function () { + var _this = this; + return Object + .keys(this._markers) + .map(function (id) { return _this._markers[id]; }); }; - DirectionDOMCalculator.prototype._configure = function (configuration) { - this._minWidth = configuration.minWidth; - this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth); + MarkerScene.prototype.has = function (id) { + return id in this._markers; }; - DirectionDOMCalculator.prototype._resize = function (element) { - this._elementWidth = element.offsetWidth; - this._elementHeight = element.offsetHeight; + MarkerScene.prototype.intersectObjects = function (_a, camera) { + var viewportX = _a[0], viewportY = _a[1]; + this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera); + var intersects = this._raycaster.intersectObjects(this._interactiveObjects); + for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) { + var intersect = intersects_1[_i]; + if (intersect.object.uuid in this._objectMarkers) { + return this._objectMarkers[intersect.object.uuid]; + } + } + return null; }; - DirectionDOMCalculator.prototype._reset = function () { - this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight); - this._containerHeight = this._getContainerHeight(this.containerWidth); - this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight); - this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight); - this._outerRadius = this._getOuterRadius(this._containerHeight); - this._innerRadius = this._getInnerRadius(this._containerHeight); - this._shadowOffset = 3; - this._containerWidthCss = this._numberToCssPixels(this._containerWidth); - this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth); - this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth)); - this._containerHeightCss = this._numberToCssPixels(this._containerHeight); - this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight)); - this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize); - this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize); - this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize); + MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) { + if (!(id in this._markers)) { + return; + } + this._markers[id].lerpAltitude(alt, alpha); + this._needsRender = true; }; - DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) { - var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth); - var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight); - var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight))); - coeff = 0.04 * Math.round(25 * coeff); - return this._minWidth + coeff * (this._maxWidth - this._minWidth); + MarkerScene.prototype.remove = function (id) { + if (!(id in this._markers)) { + return; + } + this._dispose(id); + this._needsRender = true; + }; + MarkerScene.prototype.render = function (perspectiveCamera, renderer) { + renderer.render(this._scene, perspectiveCamera); + this._needsRender = false; + }; + MarkerScene.prototype.update = function (id, position, latLon) { + if (!(id in this._markers)) { + return; + } + var marker = this._markers[id]; + marker.updatePosition(position, latLon); + this._needsRender = true; + }; + MarkerScene.prototype._dispose = function (id) { + var marker = this._markers[id]; + this._scene.remove(marker.geometry); + for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) { + var interactiveObject = _a[_i]; + var index = this._interactiveObjects.indexOf(interactiveObject); + if (index !== -1) { + this._interactiveObjects.splice(index, 1); + } + else { + console.warn("Object does not exist (" + interactiveObject.id + ") for " + id); + } + delete this._objectMarkers[interactiveObject.uuid]; + } + marker.disposeGeometry(); + delete this._markers[id]; + }; + return MarkerScene; +}()); +exports.MarkerScene = MarkerScene; +exports.default = MarkerScene; + +},{"three":240}],333:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var rbush = require("rbush"); +var Subject_1 = require("rxjs/Subject"); +var MarkerSet = /** @class */ (function () { + function MarkerSet() { + this._hash = {}; + this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]); + this._indexChanged$ = new Subject_1.Subject(); + this._updated$ = new Subject_1.Subject(); + } + Object.defineProperty(MarkerSet.prototype, "changed$", { + get: function () { + return this._indexChanged$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MarkerSet.prototype, "updated$", { + get: function () { + return this._updated$; + }, + enumerable: true, + configurable: true + }); + MarkerSet.prototype.add = function (markers) { + var updated = []; + var hash = this._hash; + var index = this._index; + for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) { + var marker = markers_1[_i]; + var id = marker.id; + if (id in hash) { + index.remove(hash[id]); + updated.push(marker); + } + var item = { + lat: marker.latLon.lat, + lon: marker.latLon.lon, + marker: marker, + }; + hash[id] = item; + index.insert(item); + } + if (updated.length > 0) { + this._updated$.next(updated); + } + if (markers.length > updated.length) { + this._indexChanged$.next(this); + } }; - DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) { - return 0.77 * containerWidth; + MarkerSet.prototype.has = function (id) { + return id in this._hash; }; - DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) { - return 0.34 * containerHeight; + MarkerSet.prototype.get = function (id) { + return this.has(id) ? this._hash[id].marker : undefined; }; - DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) { - return 0.3 * containerHeight; + MarkerSet.prototype.getAll = function () { + return this._index + .all() + .map(function (indexItem) { + return indexItem.marker; + }); }; - DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) { - return 0.31 * containerHeight; + MarkerSet.prototype.remove = function (ids) { + var hash = this._hash; + var index = this._index; + var changed = false; + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + if (!(id in hash)) { + continue; + } + var item = hash[id]; + index.remove(item); + delete hash[id]; + changed = true; + } + if (changed) { + this._indexChanged$.next(this); + } }; - DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) { - return 0.125 * containerHeight; + MarkerSet.prototype.removeAll = function () { + this._hash = {}; + this._index.clear(); + this._indexChanged$.next(this); }; - DirectionDOMCalculator.prototype._numberToCssPixels = function (value) { - return value + "px"; + MarkerSet.prototype.search = function (_a) { + var sw = _a[0], ne = _a[1]; + return this._index + .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat }) + .map(function (indexItem) { + return indexItem.marker; + }); }; - DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) { - return value > minWidth ? value : minWidth; + MarkerSet.prototype.update = function (marker) { + var hash = this._hash; + var index = this._index; + var id = marker.id; + if (!(id in hash)) { + return; + } + index.remove(hash[id]); + var item = { + lat: marker.latLon.lat, + lon: marker.latLon.lon, + marker: marker, + }; + hash[id] = item; + index.insert(item); }; - return DirectionDOMCalculator; + return MarkerSet; }()); -exports.DirectionDOMCalculator = DirectionDOMCalculator; +exports.MarkerSet = MarkerSet; +exports.default = MarkerSet; + +},{"rbush":25,"rxjs/Subject":34}],334:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = DirectionDOMCalculator; +var THREE = require("three"); +var Component_1 = require("../../../Component"); +/** + * @class CircleMarker + * + * @classdesc Non-interactive marker with a flat circle shape. The circle + * marker can not be configured to be interactive. + * + * Circle marker properties can not be updated after creation. + * + * To create and add one `CircleMarker` with default configuration + * and one with configuration use + * + * @example + * ``` + * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker( + * "id-1", + * { lat: 0, lon: 0, }); + * + * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker( + * "id-2", + * { lat: 0, lon: 0, }, + * { + * color: "#0Ff", + * opacity: 0.3, + * radius: 0.7, + * }); + * + * markerComponent.add([defaultMarker, configuredMarker]); + * ``` + */ +var CircleMarker = /** @class */ (function (_super) { + __extends(CircleMarker, _super); + function CircleMarker(id, latLon, options) { + var _this = _super.call(this, id, latLon) || this; + options = !!options ? options : {}; + _this._color = options.color != null ? options.color : 0xffffff; + _this._opacity = options.opacity != null ? options.opacity : 0.4; + _this._radius = options.radius != null ? options.radius : 1; + return _this; + } + CircleMarker.prototype._createGeometry = function (position) { + var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({ + color: this._color, + opacity: this._opacity, + transparent: true, + })); + circle.up.fromArray([0, 0, 1]); + circle.renderOrder = -1; + var group = new THREE.Object3D(); + group.add(circle); + group.position.fromArray(position); + this._geometry = group; + }; + CircleMarker.prototype._disposeGeometry = function () { + for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) { + var mesh = _a[_i]; + mesh.geometry.dispose(); + mesh.material.dispose(); + } + }; + CircleMarker.prototype._getInteractiveObjects = function () { + return []; + }; + return CircleMarker; +}(Component_1.Marker)); +exports.CircleMarker = CircleMarker; +exports.default = CircleMarker; -},{"../../Geo":210}],235:[function(require,module,exports){ -/// +},{"../../../Component":290,"three":240}],335:[function(require,module,exports){ "use strict"; -var vd = require("virtual-dom"); -var Component_1 = require("../../Component"); -var Edge_1 = require("../../Edge"); -var Geo_1 = require("../../Geo"); +/// +Object.defineProperty(exports, "__esModule", { value: true }); /** - * @class DirectionDOMRenderer - * @classdesc DOM renderer for direction arrows. + * @class Marker + * + * @classdesc Represents an abstract marker class that should be extended + * by marker implementations used in the marker component. */ -var DirectionDOMRenderer = (function () { - function DirectionDOMRenderer(configuration, element) { - this._isEdge = false; - this._spatial = new Geo_1.Spatial(); - this._calculator = new Component_1.DirectionDOMCalculator(configuration, element); - this._node = null; - this._rotation = { phi: 0, theta: 0 }; - this._epsilon = 0.5 * Math.PI / 180; - this._highlightKey = null; - this._distinguishSequence = false; - this._needsRender = false; - this._stepEdges = []; - this._turnEdges = []; - this._panoEdges = []; - this._sequenceEdgeKeys = []; - this._stepDirections = [ - Edge_1.EdgeDirection.StepForward, - Edge_1.EdgeDirection.StepBackward, - Edge_1.EdgeDirection.StepLeft, - Edge_1.EdgeDirection.StepRight, - ]; - this._turnDirections = [ - Edge_1.EdgeDirection.TurnLeft, - Edge_1.EdgeDirection.TurnRight, - Edge_1.EdgeDirection.TurnU, - ]; - this._turnNames = {}; - this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft"; - this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight"; - this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround"; - // detects IE 8-11, then Edge 20+. - var isIE = !!document.documentMode; - this._isEdge = !isIE && !!window.StyleMedia; +var Marker = /** @class */ (function () { + function Marker(id, latLon) { + this._id = id; + this._latLon = latLon; } - Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", { + Object.defineProperty(Marker.prototype, "id", { /** - * Get needs render. - * - * @returns {boolean} Value indicating whether render should be called. + * Get id. + * @returns {string} The id of the marker. */ get: function () { - return this._needsRender; + return this._id; }, enumerable: true, configurable: true }); - /** - * Renders virtual DOM elements. - * - * @description Calling render resets the needs render property. - */ - DirectionDOMRenderer.prototype.render = function (navigator) { - this._needsRender = false; - var rotation = this._rotation; - var steps = []; - var turns = []; - if (this._node.pano) { - steps = steps.concat(this._createPanoArrows(navigator, rotation)); - } - else { - steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation)); - steps = steps.concat(this._createStepArrows(navigator, rotation)); - turns = turns.concat(this._createTurnArrows(navigator)); + Object.defineProperty(Marker.prototype, "geometry", { + get: function () { + return this._geometry; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Marker.prototype, "latLon", { + /** + * Get lat lon. + * @returns {ILatLon} The geographic coordinates of the marker. + */ + get: function () { + return this._latLon; + }, + enumerable: true, + configurable: true + }); + Marker.prototype.createGeometry = function (position) { + if (!!this._geometry) { + return; } - return this._getContainer(steps, turns, rotation); + this._createGeometry(position); + // update matrix world if raycasting occurs before first render + this._geometry.updateMatrixWorld(true); }; - DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) { - this._setEdges(edgeStatus, sequence); - this._setNeedsRender(); + Marker.prototype.disposeGeometry = function () { + if (!this._geometry) { + return; + } + this._disposeGeometry(); + this._geometry = undefined; }; - /** - * Set node for which to show edges. - * - * @param {Node} node - */ - DirectionDOMRenderer.prototype.setNode = function (node) { - this._node = node; - this._clearEdges(); - this._setNeedsRender(); + Marker.prototype.getInteractiveObjects = function () { + if (!this._geometry) { + return []; + } + return this._getInteractiveObjects(); }; - /** - * Set the render camera to use for calculating rotations. - * - * @param {RenderCamera} renderCamera - */ - DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) { - var camera = renderCamera.camera; - var direction = this._directionFromCamera(camera); - var rotation = this._getRotation(direction, camera.up); - if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) { + Marker.prototype.lerpAltitude = function (alt, alpha) { + if (!this._geometry) { return; } - this._rotation = rotation; - this._setNeedsRender(); + this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt; }; - /** - * Set configuration values. - * - * @param {IDirectionConfiguration} configuration - */ - DirectionDOMRenderer.prototype.setConfiguration = function (configuration) { - var needsRender = false; - if (this._highlightKey !== configuration.highlightKey || - this._distinguishSequence !== configuration.distinguishSequence) { - this._highlightKey = configuration.highlightKey; - this._distinguishSequence = configuration.distinguishSequence; - needsRender = true; + Marker.prototype.updatePosition = function (position, latLon) { + if (!!latLon) { + this._latLon.lat = latLon.lat; + this._latLon.lon = latLon.lon; } - if (this._calculator.minWidth !== configuration.minWidth || - this._calculator.maxWidth !== configuration.maxWidth) { - this._calculator.configure(configuration); - needsRender = true; + if (!this._geometry) { + return; } - if (needsRender) { - this._setNeedsRender(); + this._geometry.position.fromArray(position); + this._geometry.updateMatrixWorld(true); + }; + return Marker; +}()); +exports.Marker = Marker; +exports.default = Marker; + +},{}],336:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var Component_1 = require("../../../Component"); +/** + * @class SimpleMarker + * + * @classdesc Interactive marker with ice cream shape. The sphere + * inside the ice cream can be configured to be interactive. + * + * Simple marker properties can not be updated after creation. + * + * To create and add one `SimpleMarker` with default configuration + * (non-interactive) and one interactive with configuration use + * + * @example + * ``` + * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker( + * "id-1", + * { lat: 0, lon: 0, }); + * + * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker( + * "id-2", + * { lat: 0, lon: 0, }, + * { + * ballColor: "#00f", + * ballOpacity: 0.5, + * color: "#00f", + * interactive: true, + * opacity: 0.3, + * radius: 0.7, + * }); + * + * markerComponent.add([defaultMarker, interactiveMarker]); + * ``` + */ +var SimpleMarker = /** @class */ (function (_super) { + __extends(SimpleMarker, _super); + function SimpleMarker(id, latLon, options) { + var _this = _super.call(this, id, latLon) || this; + options = !!options ? options : {}; + _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000; + _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8; + _this._circleToRayAngle = 2; + _this._color = options.color != null ? options.color : 0xff0000; + _this._interactive = !!options.interactive; + _this._opacity = options.opacity != null ? options.opacity : 0.4; + _this._radius = options.radius != null ? options.radius : 1; + return _this; + } + SimpleMarker.prototype._createGeometry = function (position) { + var radius = this._radius; + var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({ + color: this._color, + opacity: this._opacity, + transparent: true, + })); + cone.renderOrder = 1; + var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({ + color: this._ballColor, + opacity: this._ballOpacity, + transparent: true, + })); + ball.position.z = this._markerHeight(radius); + var group = new THREE.Object3D(); + group.add(ball); + group.add(cone); + group.position.fromArray(position); + this._geometry = group; + }; + SimpleMarker.prototype._disposeGeometry = function () { + for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) { + var mesh = _a[_i]; + mesh.geometry.dispose(); + mesh.material.dispose(); + } + }; + SimpleMarker.prototype._getInteractiveObjects = function () { + return this._interactive ? [this._geometry.children[0]] : []; + }; + SimpleMarker.prototype._markerHeight = function (radius) { + var t = Math.tan(Math.PI - this._circleToRayAngle); + return radius * Math.sqrt(1 + t * t); + }; + SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) { + var geometry = new THREE.Geometry(); + widthSegments = Math.max(3, Math.floor(widthSegments) || 8); + heightSegments = Math.max(2, Math.floor(heightSegments) || 6); + var height = this._markerHeight(radius); + var vertices = []; + for (var y = 0; y <= heightSegments; ++y) { + var verticesRow = []; + for (var x = 0; x <= widthSegments; ++x) { + var u = x / widthSegments * Math.PI * 2; + var v = y / heightSegments * Math.PI; + var r = void 0; + if (v < this._circleToRayAngle) { + r = radius; + } + else { + var t = Math.tan(v - this._circleToRayAngle); + r = radius * Math.sqrt(1 + t * t); + } + var vertex = new THREE.Vector3(); + vertex.x = r * Math.cos(u) * Math.sin(v); + vertex.y = r * Math.sin(u) * Math.sin(v); + vertex.z = r * Math.cos(v) + height; + geometry.vertices.push(vertex); + verticesRow.push(geometry.vertices.length - 1); + } + vertices.push(verticesRow); } - }; - /** - * Detect the element's width and height and resize - * elements accordingly. - * - * @param {HTMLElement} element Viewer container element. - */ - DirectionDOMRenderer.prototype.resize = function (element) { - this._calculator.resize(element); - this._setNeedsRender(); - }; - DirectionDOMRenderer.prototype._setNeedsRender = function () { - if (this._node != null) { - this._needsRender = true; + for (var y = 0; y < heightSegments; ++y) { + for (var x = 0; x < widthSegments; ++x) { + var v1 = vertices[y][x + 1]; + var v2 = vertices[y][x]; + var v3 = vertices[y + 1][x]; + var v4 = vertices[y + 1][x + 1]; + var n1 = geometry.vertices[v1].clone().normalize(); + var n2 = geometry.vertices[v2].clone().normalize(); + var n3 = geometry.vertices[v3].clone().normalize(); + var n4 = geometry.vertices[v4].clone().normalize(); + geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4])); + geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()])); + } } + geometry.computeFaceNormals(); + geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height); + return geometry; }; - DirectionDOMRenderer.prototype._clearEdges = function () { - this._stepEdges = []; - this._turnEdges = []; - this._panoEdges = []; - this._sequenceEdgeKeys = []; + return SimpleMarker; +}(Component_1.Marker)); +exports.SimpleMarker = SimpleMarker; +exports.default = SimpleMarker; + +},{"../../../Component":290,"three":240}],337:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) { - this._stepEdges = []; - this._turnEdges = []; - this._panoEdges = []; - this._sequenceEdgeKeys = []; - for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { - var edge = _a[_i]; - var direction = edge.data.direction; - if (this._stepDirections.indexOf(direction) > -1) { - this._stepEdges.push(edge); - continue; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../../Component"); +/** + * The `BounceHandler` ensures that the viewer bounces back to the image + * when drag panning outside of the image edge. + */ +var BounceHandler = /** @class */ (function (_super) { + __extends(BounceHandler, _super); + function BounceHandler(component, container, navigator, viewportCoords, spatial) { + var _this = _super.call(this, component, container, navigator) || this; + _this._spatial = spatial; + _this._viewportCoords = viewportCoords; + _this._basicDistanceThreshold = 1e-3; + _this._basicRotationThreshold = 5e-2; + _this._bounceCoeff = 1e-1; + return _this; + } + BounceHandler.prototype._enable = function () { + var _this = this; + var inTransition$ = this._navigator.stateService.currentState$ + .map(function (frame) { + return frame.state.alpha < 1; + }); + this._bounceSubscription = Observable_1.Observable + .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$) + .map(function (noForce) { + return noForce[0] || noForce[1] || noForce[2] || noForce[3]; + }) + .distinctUntilChanged() + .switchMap(function (noForce) { + return noForce ? + Observable_1.Observable.empty() : + Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first()); + }) + .subscribe(function (args) { + var renderCamera = args[0]; + var perspectiveCamera = renderCamera.perspective; + var transform = args[1]; + if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) { + return; } - if (this._turnDirections.indexOf(direction) > -1) { - this._turnEdges.push(edge); - continue; + if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) { + return; } - if (edge.data.direction === Edge_1.EdgeDirection.Pano) { - this._panoEdges.push(edge); + var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom); + var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera); + if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) { + return; } - } - if (this._distinguishSequence && sequence != null) { - var edges = this._panoEdges - .concat(this._stepEdges) - .concat(this._turnEdges); - for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) { - var edge = edges_1[_b]; - var edgeKey = edge.to; - for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) { - var sequenceKey = _d[_c]; - if (sequenceKey === edgeKey) { - this._sequenceEdgeKeys.push(edgeKey); - break; - } - } + var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera); + var basicX = 0; + var basicY = 0; + if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold && + basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) { + return; } - } + if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold && + Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) { + return; + } + var coeff = _this._bounceCoeff; + if (basicDistances[1] > 0 && basicDistances[3] === 0) { + basicX = -coeff * basicDistances[1]; + } + else if (basicDistances[1] === 0 && basicDistances[3] > 0) { + basicX = coeff * basicDistances[3]; + } + else if (basicDistances[1] > 0 && basicDistances[3] > 0) { + basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2; + } + if (basicDistances[0] > 0 && basicDistances[2] === 0) { + basicY = coeff * basicDistances[0]; + } + else if (basicDistances[0] === 0 && basicDistances[2] > 0) { + basicY = -coeff * basicDistances[2]; + } + else if (basicDistances[0] > 0 && basicDistances[2] > 0) { + basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2; + } + var rotationThreshold = _this._basicRotationThreshold; + basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold); + basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold); + _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]); + }); }; - DirectionDOMRenderer.prototype._directionFromCamera = function (camera) { - return camera.lookat.clone().sub(camera.position); + BounceHandler.prototype._disable = function () { + this._bounceSubscription.unsubscribe(); }; - DirectionDOMRenderer.prototype._getRotation = function (direction, up) { - var upProjection = direction.clone().dot(up); - var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection)); - var phi = Math.atan2(planeProjection.y, planeProjection.x); - var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]); - return { phi: phi, theta: theta }; + BounceHandler.prototype._getConfiguration = function (enable) { + return {}; }; - DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) { - var arrows = []; - for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) { - var panoEdge = _a[_i]; - arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano")); - } - for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) { - var stepEdge = _c[_b]; - arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction)); - } - return arrows; + return BounceHandler; +}(Component_1.HandlerBase)); +exports.BounceHandler = BounceHandler; +exports.default = BounceHandler; + +},{"../../Component":290,"rxjs/Observable":29}],338:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) { - var threshold = Math.PI / 8; - var relativePhi = rotation.phi; - switch (direction) { - case Edge_1.EdgeDirection.StepBackward: - relativePhi = rotation.phi - Math.PI; - break; - case Edge_1.EdgeDirection.StepLeft: - relativePhi = rotation.phi + Math.PI / 2; - break; - case Edge_1.EdgeDirection.StepRight: - relativePhi = rotation.phi - Math.PI / 2; - break; - default: - break; - } - if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) { - return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep"); - } - return this._createVNodeDisabled(key, azimuth, rotation); +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../../Component"); +/** + * The `DoubleClickZoomHandler` allows the user to zoom the viewer image at a point by double clicking. + * + * @example + * ``` + * var mouseComponent = viewer.getComponent("mouse"); + * + * mouseComponent.doubleClickZoom.disable(); + * mouseComponent.doubleClickZoom.enable(); + * + * var isEnabled = mouseComponent.doubleClickZoom.isEnabled; + * ``` + */ +var DoubleClickZoomHandler = /** @class */ (function (_super) { + __extends(DoubleClickZoomHandler, _super); + function DoubleClickZoomHandler(component, container, navigator, viewportCoords) { + var _this = _super.call(this, component, container, navigator) || this; + _this._viewportCoords = viewportCoords; + return _this; + } + DoubleClickZoomHandler.prototype._enable = function () { + var _this = this; + this._zoomSubscription = Observable_1.Observable + .merge(this._container.mouseService + .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$ + .map(function (e) { + var touch = e.touches[0]; + return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey }; + })) + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .subscribe(function (_a) { + var event = _a[0], render = _a[1], transform = _a[2]; + var element = _this._container.element; + var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1]; + var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective); + var reference = transform.projectBasic(unprojected.toArray()); + var delta = !!event.shiftKey ? -1 : 1; + _this._navigator.stateService.zoomIn(delta, reference); + }); }; - DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) { - var arrows = []; - for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) { - var panoEdge = _a[_i]; - arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true)); - } - return arrows; + DoubleClickZoomHandler.prototype._disable = function () { + this._zoomSubscription.unsubscribe(); }; - DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) { - var arrows = []; - for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) { - var stepEdge = _a[_i]; - arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction)); - } - return arrows; + DoubleClickZoomHandler.prototype._getConfiguration = function (enable) { + return { doubleClickZoom: enable }; + }; + return DoubleClickZoomHandler; +}(Component_1.HandlerBase)); +exports.DoubleClickZoomHandler = DoubleClickZoomHandler; +exports.default = DoubleClickZoomHandler; + +},{"../../Component":290,"rxjs/Observable":29}],339:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../../Component"); +/** + * The `DragPanHandler` allows the user to pan the viewer image by clicking and dragging the cursor. + * + * @example + * ``` + * var mouseComponent = viewer.getComponent("mouse"); + * + * mouseComponent.dragPan.disable(); + * mouseComponent.dragPan.enable(); + * + * var isEnabled = mouseComponent.dragPan.isEnabled; + * ``` + */ +var DragPanHandler = /** @class */ (function (_super) { + __extends(DragPanHandler, _super); + function DragPanHandler(component, container, navigator, viewportCoords, spatial) { + var _this = _super.call(this, component, container, navigator) || this; + _this._spatial = spatial; + _this._viewportCoords = viewportCoords; + _this._basicRotationThreshold = 5e-2; + _this._forceCoeff = 2e-1; + return _this; + } + DragPanHandler.prototype._enable = function () { + var _this = this; + var draggingStarted$ = this._container.mouseService + .filtered$(this._component.name, this._container.mouseService.mouseDragStart$) + .map(function (event) { + return true; + }) + .share(); + var draggingStopped$ = this._container.mouseService + .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$) + .map(function (event) { + return false; + }) + .share(); + this._activeMouseSubscription = Observable_1.Observable + .merge(draggingStarted$, draggingStopped$) + .subscribe(this._container.mouseService.activate$); + this._preventDefaultSubscription = Observable_1.Observable + .merge(draggingStarted$, draggingStopped$) + .switchMap(function (dragging) { + return dragging ? + _this._container.mouseService.documentMouseMove$ : + Observable_1.Observable.empty(); + }) + .merge(this._container.touchService.touchMove$) + .subscribe(function (event) { + event.preventDefault(); // prevent selection of content outside the viewer + }); + var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$ + .map(function (event) { + return true; + }); + var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$ + .map(function (event) { + return false; + }); + this._activeTouchSubscription = Observable_1.Observable + .merge(touchMovingStarted$, touchMovingStopped$) + .subscribe(this._container.touchService.activate$); + var basicRotation$ = this._navigator.stateService.currentState$ + .map(function (frame) { + return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1; + }) + .distinctUntilChanged() + .switchMap(function (enable) { + if (!enable) { + return Observable_1.Observable.empty(); + } + var mouseDrag$ = _this._container.mouseService + .filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$) + .switchMap(function (mouseDragStart) { + return Observable_1.Observable + .of(mouseDragStart) + .concat(_this._container.mouseService + .filtered$(_this._component.name, _this._container.mouseService.mouseDrag$)) + .merge(_this._container.mouseService + .filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$) + .map(function (e) { + return null; + })) + .takeWhile(function (e) { + return !!e; + }) + .startWith(null); + }) + .pairwise() + .filter(function (pair) { + return pair[0] != null && pair[1] != null; + }); + var singleTouchDrag$ = Observable_1.Observable + .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; })) + .map(function (event) { + return event != null && event.touches.length > 0 ? + event.touches[0] : null; + }) + .pairwise() + .filter(function (pair) { + return pair[0] != null && pair[1] != null; + }); + return Observable_1.Observable + .merge(mouseDrag$, singleTouchDrag$); + }) + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$) + .map(function (_a) { + var events = _a[0], render = _a[1], transform = _a[2], c = _a[3]; + var camera = c.clone(); + var previousEvent = events[0]; + var event = events[1]; + var movementX = event.clientX - previousEvent.clientX; + var movementY = event.clientY - previousEvent.clientY; + var element = _this._container.element; + var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1]; + var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective) + .sub(render.perspective.position); + var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective) + .sub(render.perspective.position); + var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective) + .sub(render.perspective.position); + var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection); + var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection); + var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1)); + var upQuaternionInverse = upQuaternion.clone().inverse(); + var offset = new THREE.Vector3(); + offset.copy(camera.lookat).sub(camera.position); + offset.applyQuaternion(upQuaternion); + var length = offset.length(); + var phi = Math.atan2(offset.y, offset.x); + phi += deltaPhi; + var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z); + theta += deltaTheta; + theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta)); + offset.x = Math.sin(theta) * Math.cos(phi); + offset.y = Math.sin(theta) * Math.sin(phi); + offset.z = Math.cos(theta); + offset.applyQuaternion(upQuaternionInverse); + var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length)); + var basic = transform.projectBasic(lookat.toArray()); + var original = transform.projectBasic(camera.lookat.toArray()); + var x = basic[0] - original[0]; + var y = basic[1] - original[1]; + if (Math.abs(x) > 1) { + x = 0; + } + else if (x > 0.5) { + x = x - 1; + } + else if (x < -0.5) { + x = x + 1; + } + var rotationThreshold = _this._basicRotationThreshold; + x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold); + y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold); + if (transform.fullPano) { + return [x, y]; + } + var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective); + var coeff = _this._forceCoeff; + if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) { + y /= Math.max(1, coeff * pixelDistances[0]); + } + if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) { + x /= Math.max(1, coeff * pixelDistances[1]); + } + if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) { + y /= Math.max(1, coeff * pixelDistances[2]); + } + if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) { + x /= Math.max(1, coeff * pixelDistances[3]); + } + return [x, y]; + }) + .share(); + this._rotateBasicWithoutInertiaSubscription = basicRotation$ + .subscribe(function (basicRotation) { + _this._navigator.stateService.rotateBasicWithoutInertia(basicRotation); + }); + this._rotateBasicSubscription = basicRotation$ + .scan(function (rotationBuffer, rotation) { + _this._drainBuffer(rotationBuffer); + rotationBuffer.push([Date.now(), rotation]); + return rotationBuffer; + }, []) + .sample(Observable_1.Observable + .merge(this._container.mouseService.filtered$(this._component.name, this._container.mouseService.mouseDragEnd$), this._container.touchService.singleTouchDragEnd$)) + .map(function (rotationBuffer) { + var drainedBuffer = _this._drainBuffer(rotationBuffer.slice()); + var basicRotation = [0, 0]; + for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) { + var rotation = drainedBuffer_1[_i]; + basicRotation[0] += rotation[1][0]; + basicRotation[1] += rotation[1][1]; + } + var count = drainedBuffer.length; + if (count > 0) { + basicRotation[0] /= count; + basicRotation[1] /= count; + } + return basicRotation; + }) + .subscribe(function (basicRotation) { + _this._navigator.stateService.rotateBasic(basicRotation); + }); }; - DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) { - var turns = []; - for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) { - var turnEdge = _a[_i]; - var direction = turnEdge.data.direction; - var name_1 = this._turnNames[direction]; - turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction)); + DragPanHandler.prototype._disable = function () { + this._activeMouseSubscription.unsubscribe(); + this._activeTouchSubscription.unsubscribe(); + this._preventDefaultSubscription.unsubscribe(); + this._rotateBasicSubscription.unsubscribe(); + this._rotateBasicWithoutInertiaSubscription.unsubscribe(); + this._activeMouseSubscription = null; + this._activeTouchSubscription = null; + this._preventDefaultSubscription = null; + this._rotateBasicSubscription = null; + }; + DragPanHandler.prototype._getConfiguration = function (enable) { + return { dragPan: enable }; + }; + DragPanHandler.prototype._drainBuffer = function (buffer) { + var cutoff = 50; + var now = Date.now(); + while (buffer.length > 0 && now - buffer[0][0] > cutoff) { + buffer.shift(); } - return turns; - }; - DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) { - var onClick = function (e) { - navigator.moveToKey$(key) - .subscribe(function (node) { return; }, function (error) { console.error(error); }); - }; - return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically); - }; - DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) { - var onClick = function (e) { - navigator.moveDir$(direction) - .subscribe(function (node) { return; }, function (error) { console.error(error); }); - }; - return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick); + return buffer; }; - DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) { - var onClick = function (e) { - navigator.moveDir$(direction) - .subscribe(function (node) { return; }, function (error) { console.error(error); }); - }; - var style = { - height: this._calculator.turnCircleSizeCss, - transform: "rotate(0)", - width: this._calculator.turnCircleSizeCss, - }; - switch (direction) { - case Edge_1.EdgeDirection.TurnLeft: - style.left = "5px"; - style.top = "5px"; - break; - case Edge_1.EdgeDirection.TurnRight: - style.right = "5px"; - style.top = "5px"; - break; - case Edge_1.EdgeDirection.TurnU: - style.left = "5px"; - style.bottom = "5px"; - break; - default: - break; - } - var circleProperties = { - attributes: { - "data-key": key, - }, - onclick: onClick, - style: style, - }; - var circleClassName = "TurnCircle"; - if (this._sequenceEdgeKeys.indexOf(key) > -1) { - circleClassName += "Sequence"; - } - if (this._highlightKey === key) { - circleClassName += "Highlight"; - } - var turn = vd.h("div." + className, {}, []); - return vd.h("div." + circleClassName, circleProperties, [turn]); + return DragPanHandler; +}(Component_1.HandlerBase)); +exports.DragPanHandler = DragPanHandler; +exports.default = DragPanHandler; + +},{"../../Component":290,"rxjs/Observable":29,"three":240}],340:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) { - return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled"); +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../Component"); +var Geo_1 = require("../../Geo"); +/** + * @class MouseComponent + * + * @classdesc Component handling mouse and touch events for camera movement. + * + * To retrive and use the mouse component + * + * @example + * ``` + * var viewer = new Mapillary.Viewer( + * "", + * "", + * ""); + * + * var mouseComponent = viewer.getComponent("mouse"); + * ``` + */ +var MouseComponent = /** @class */ (function (_super) { + __extends(MouseComponent, _super); + function MouseComponent(name, container, navigator) { + var _this = _super.call(this, name, container, navigator) || this; + var spatial = new Geo_1.Spatial(); + var viewportCoords = new Geo_1.ViewportCoords(); + _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial); + _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords); + _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial); + _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords); + _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords); + return _this; + } + Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", { + /** + * Get double click zoom. + * + * @returns {DoubleClickZoomHandler} The double click zoom handler. + */ + get: function () { + return this._doubleClickZoomHandler; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseComponent.prototype, "dragPan", { + /** + * Get drag pan. + * + * @returns {DragPanHandler} The drag pan handler. + */ + get: function () { + return this._dragPanHandler; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseComponent.prototype, "scrollZoom", { + /** + * Get scroll zoom. + * + * @returns {ScrollZoomHandler} The scroll zoom handler. + */ + get: function () { + return this._scrollZoomHandler; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseComponent.prototype, "touchZoom", { + /** + * Get touch zoom. + * + * @returns {TouchZoomHandler} The touch zoom handler. + */ + get: function () { + return this._touchZoomHandler; + }, + enumerable: true, + configurable: true + }); + MouseComponent.prototype._activate = function () { + var _this = this; + this._bounceHandler.enable(); + this._configurationSubscription = this._configuration$ + .subscribe(function (configuration) { + if (configuration.doubleClickZoom) { + _this._doubleClickZoomHandler.enable(); + } + else { + _this._doubleClickZoomHandler.disable(); + } + if (configuration.dragPan) { + _this._dragPanHandler.enable(); + } + else { + _this._dragPanHandler.disable(); + } + if (configuration.scrollZoom) { + _this._scrollZoomHandler.enable(); + } + else { + _this._scrollZoomHandler.disable(); + } + if (configuration.touchZoom) { + _this._touchZoomHandler.enable(); + } + else { + _this._touchZoomHandler.disable(); + } + }); + this._container.mouseService.claimMouse(this._name, 0); }; - DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) { - var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi); - // rotate 90 degrees clockwise and flip over X-axis - var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth); - var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight); - var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi); - var shadowOffset = this._calculator.shadowOffset; - var shadowTranslationX = -shadowOffset * shadowTranslation[1]; - var shadowTranslationY = shadowOffset * shadowTranslation[0]; - var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))"; - var properties = { - style: { - "-webkit-filter": filter, - filter: filter, - }, - }; - var chevron = vd.h("div." + className, properties, []); - var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi); - var circleTransform = shiftVertically ? - "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" : - "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)"; - var circleProperties = { - attributes: { "data-key": key }, - onclick: onClick, - style: { - height: this._calculator.stepCircleSizeCss, - marginLeft: this._calculator.stepCircleMarginCss, - marginTop: this._calculator.stepCircleMarginCss, - transform: circleTransform, - width: this._calculator.stepCircleSizeCss, - }, - }; - if (this._sequenceEdgeKeys.indexOf(key) > -1) { - circleClassName += "Sequence"; - } - if (this._highlightKey === key) { - circleClassName += "Highlight"; - } - return vd.h("div." + circleClassName, circleProperties, [chevron]); + MouseComponent.prototype._deactivate = function () { + this._container.mouseService.unclaimMouse(this._name); + this._configurationSubscription.unsubscribe(); + this._bounceHandler.disable(); + this._doubleClickZoomHandler.disable(); + this._dragPanHandler.disable(); + this._scrollZoomHandler.disable(); + this._touchZoomHandler.disable(); }; - DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) { - // edge does not handle hover on perspective transforms. - var transform = this._isEdge ? - "rotateX(60deg)" : - "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)"; - var perspectiveStyle = { - bottom: this._calculator.containerBottomCss, - height: this._calculator.containerHeightCss, - left: this._calculator.containerLeftCss, - marginLeft: this._calculator.containerMarginCss, - transform: transform, - width: this._calculator.containerWidthCss, - }; - return vd.h("div.DirectionsPerspective", { style: perspectiveStyle }, turns.concat(steps)); + MouseComponent.prototype._getDefaultConfiguration = function () { + return { doubleClickZoom: false, dragPan: true, scrollZoom: true, touchZoom: true }; }; - return DirectionDOMRenderer; -}()); -exports.DirectionDOMRenderer = DirectionDOMRenderer; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = DirectionDOMRenderer; + /** @inheritdoc */ + MouseComponent.componentName = "mouse"; + return MouseComponent; +}(Component_1.Component)); +exports.MouseComponent = MouseComponent; +Component_1.ComponentService.register(MouseComponent); +exports.default = MouseComponent; -},{"../../Component":207,"../../Edge":208,"../../Geo":210,"virtual-dom":163}],236:[function(require,module,exports){ +},{"../../Component":290,"../../Geo":293}],341:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Observable_1 = require("rxjs/Observable"); -var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/observable/of"); -require("rxjs/add/operator/debounceTime"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/switchMap"); -require("rxjs/add/operator/withLatestFrom"); +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Component_1 = require("../../Component"); -var Render_1 = require("../../Render"); -var Graph_1 = require("../../Graph"); -var Utils_1 = require("../../Utils"); -var ImagePlaneComponent = (function (_super) { - __extends(ImagePlaneComponent, _super); - function ImagePlaneComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._rendererOperation$ = new Subject_1.Subject(); - this._rendererCreator$ = new Subject_1.Subject(); - this._rendererDisposer$ = new Subject_1.Subject(); - this._renderer$ = this._rendererOperation$ - .scan(function (renderer, operation) { - return operation(renderer); - }, null) - .filter(function (renderer) { - return renderer != null; - }) - .distinctUntilChanged(undefined, function (renderer) { - return renderer.frameId; +/** + * The `ScrollZoomHandler` allows the user to zoom the viewer image by scrolling. + * + * @example + * ``` + * var mouseComponent = viewer.getComponent("mouse"); + * + * mouseComponent.scrollZoom.disable(); + * mouseComponent.scrollZoom.enable(); + * + * var isEnabled = mouseComponent.scrollZoom.isEnabled; + * ``` + */ +var ScrollZoomHandler = /** @class */ (function (_super) { + __extends(ScrollZoomHandler, _super); + function ScrollZoomHandler(component, container, navigator, viewportCoords) { + var _this = _super.call(this, component, container, navigator) || this; + _this._viewportCoords = viewportCoords; + return _this; + } + ScrollZoomHandler.prototype._enable = function () { + var _this = this; + this._container.mouseService.claimWheel(this._component.name, 0); + this._preventDefaultSubscription = this._container.mouseService.mouseWheel$ + .subscribe(function (event) { + event.preventDefault(); }); - this._rendererCreator$ - .map(function () { - return function (renderer) { - if (renderer != null) { - throw new Error("Multiple image plane states can not be created at the same time"); - } - return new Component_1.ImagePlaneGLRenderer(); - }; + this._zoomSubscription = this._container.mouseService + .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$) + .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) { + return [w, f]; }) - .subscribe(this._rendererOperation$); - this._rendererDisposer$ - .map(function () { - return function (renderer) { - renderer.dispose(); - return null; - }; + .filter(function (args) { + var state = args[1].state; + return state.currentNode.fullPano || state.nodesAhead < 1; }) - .subscribe(this._rendererOperation$); - } - ImagePlaneComponent.prototype._activate = function () { - var _this = this; - this._rendererSubscription = this._renderer$ - .map(function (renderer) { - var renderHash = { - name: _this._name, - render: { - frameId: renderer.frameId, - needsRender: renderer.needsRender, - render: renderer.render.bind(renderer), - stage: Render_1.GLRenderStage.Background, - }, - }; - renderer.clearNeedsRender(); - return renderHash; + .map(function (args) { + return args[0]; }) - .subscribe(this._container.glRenderer.render$); - this._rendererCreator$.next(null); - this._stateSubscription = this._navigator.stateService.currentState$ - .map(function (frame) { - return function (renderer) { - renderer.updateFrame(frame); - return renderer; - }; + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) { + return [w, r, t]; }) - .subscribe(this._rendererOperation$); - this._nodeSubscription = Observable_1.Observable - .combineLatest(this._navigator.stateService.currentNode$, this._configuration$) - .debounceTime(1000) - .withLatestFrom(this._navigator.stateService.currentTransform$, function (nc, t) { - return [nc[0], nc[1], t]; - }) - .map(function (params) { - var node = params[0]; - var configuration = params[1]; - var transform = params[2]; - var imageSize = Utils_1.Settings.maxImageSize; - if (node.pano) { - if (configuration.maxPanoramaResolution === "high") { - imageSize = Math.max(imageSize, Math.min(4096, Math.max(transform.width, transform.height))); - } - else if (configuration.maxPanoramaResolution === "full") { - imageSize = Math.max(imageSize, transform.width, transform.height); - } + .subscribe(function (args) { + var event = args[0]; + var render = args[1]; + var transform = args[2]; + var element = _this._container.element; + var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1]; + var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective); + var reference = transform.projectBasic(unprojected.toArray()); + var deltaY = event.deltaY; + if (event.deltaMode === 1) { + deltaY = 40 * deltaY; } - return [node, imageSize]; - }) - .filter(function (params) { - var node = params[0]; - var imageSize = params[1]; - return node.pano ? - imageSize > Utils_1.Settings.basePanoramaSize : - imageSize > Utils_1.Settings.baseImageSize; - }) - .switchMap(function (params) { - var node = params[0]; - var imageSize = params[1]; - var image$ = node.pano && imageSize > Utils_1.Settings.maxImageSize ? - Graph_1.ImageLoader.loadDynamic(node.key, imageSize) : - Graph_1.ImageLoader.loadThumbnail(node.key, imageSize); - return image$ - .filter(function (statusObject) { - return statusObject.object != null; - }) - .first() - .map(function (statusObject) { - return statusObject.object; - }) - .zip(Observable_1.Observable.of(node), function (i, n) { - return [i, n]; - }) - .catch(function (error, caught) { - console.error("Failed to fetch high res image (" + node.key + ")", error); - return Observable_1.Observable.empty(); - }); - }) - .map(function (imn) { - return function (renderer) { - renderer.updateTexture(imn[0], imn[1]); - return renderer; - }; - }) - .subscribe(this._rendererOperation$); + else if (event.deltaMode === 2) { + deltaY = 800 * deltaY; + } + var canvasSize = _this._viewportCoords.containerToCanvas(element); + var zoom = -3 * deltaY / canvasSize[1]; + _this._navigator.stateService.zoomIn(zoom, reference); + }); }; - ImagePlaneComponent.prototype._deactivate = function () { - this._rendererDisposer$.next(null); - this._rendererSubscription.unsubscribe(); - this._stateSubscription.unsubscribe(); - this._nodeSubscription.unsubscribe(); + ScrollZoomHandler.prototype._disable = function () { + this._container.mouseService.unclaimWheel(this._component.name); + this._preventDefaultSubscription.unsubscribe(); + this._zoomSubscription.unsubscribe(); + this._preventDefaultSubscription = null; + this._zoomSubscription = null; }; - ImagePlaneComponent.prototype._getDefaultConfiguration = function () { - return { maxPanoramaResolution: "auto" }; + ScrollZoomHandler.prototype._getConfiguration = function (enable) { + return { scrollZoom: enable }; }; - ImagePlaneComponent.componentName = "imagePlane"; - return ImagePlaneComponent; -}(Component_1.Component)); -exports.ImagePlaneComponent = ImagePlaneComponent; -Component_1.ComponentService.register(ImagePlaneComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ImagePlaneComponent; + return ScrollZoomHandler; +}(Component_1.HandlerBase)); +exports.ScrollZoomHandler = ScrollZoomHandler; +exports.default = ScrollZoomHandler; -},{"../../Component":207,"../../Graph":211,"../../Render":213,"../../Utils":215,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/of":44,"rxjs/add/operator/debounceTime":51,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/scan":68,"rxjs/add/operator/switchMap":73,"rxjs/add/operator/withLatestFrom":76}],237:[function(require,module,exports){ -/// +},{"../../Component":290}],342:[function(require,module,exports){ "use strict"; -var THREE = require("three"); -var Component_1 = require("../../Component"); -var ImagePlaneFactory = (function () { - function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) { - this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200; - this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200; - } - ImagePlaneFactory.prototype.createMesh = function (node, transform) { - var mesh = node.pano ? - this._createImageSphere(node, transform) : - this._createImagePlane(node, transform); - return mesh; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - ImagePlaneFactory.prototype._createImageSphere = function (node, transform) { - var texture = this._createTexture(node.image); - var materialParameters = this._createSphereMaterialParameters(transform, texture); - var material = new THREE.ShaderMaterial(materialParameters); - var mesh = this._useMesh(transform, node) ? - new THREE.Mesh(this._getImageSphereGeo(transform, node), material) : - new THREE.Mesh(this._getFlatImageSphereGeo(transform), material); - return mesh; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../../Component"); +/** + * The `TouchZoomHandler` allows the user to zoom the viewer image by pinching on a touchscreen. + * + * @example + * ``` + * var mouseComponent = viewer.getComponent("mouse"); + * + * mouseComponent.touchZoom.disable(); + * mouseComponent.touchZoom.enable(); + * + * var isEnabled = mouseComponent.touchZoom.isEnabled; + * ``` + */ +var TouchZoomHandler = /** @class */ (function (_super) { + __extends(TouchZoomHandler, _super); + function TouchZoomHandler(component, container, navigator, viewportCoords) { + var _this = _super.call(this, component, container, navigator) || this; + _this._viewportCoords = viewportCoords; + return _this; + } + TouchZoomHandler.prototype._enable = function () { + var _this = this; + this._preventDefaultSubscription = this._container.touchService.pinch$ + .subscribe(function (pinch) { + pinch.originalEvent.preventDefault(); + }); + var pinchStarted$ = this._container.touchService.pinchStart$ + .map(function (event) { + return true; + }); + var pinchStopped$ = this._container.touchService.pinchEnd$ + .map(function (event) { + return false; + }); + this._activeSubscription = Observable_1.Observable + .merge(pinchStarted$, pinchStopped$) + .subscribe(this._container.touchService.activate$); + this._zoomSubscription = this._container.touchService.pinch$ + .withLatestFrom(this._navigator.stateService.currentState$) + .filter(function (args) { + var state = args[1].state; + return state.currentNode.fullPano || state.nodesAhead < 1; + }) + .map(function (args) { + return args[0]; + }) + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .subscribe(function (_a) { + var pinch = _a[0], render = _a[1], transform = _a[2]; + var element = _this._container.element; + var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1]; + var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective); + var reference = transform.projectBasic(unprojected.toArray()); + var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1]; + var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight); + _this._navigator.stateService.zoomIn(zoom, reference); + }); }; - ImagePlaneFactory.prototype._createImagePlane = function (node, transform) { - var texture = this._createTexture(node.image); - var materialParameters = this._createPlaneMaterialParameters(transform, texture); - var material = new THREE.ShaderMaterial(materialParameters); - var geometry = this._useMesh(transform, node) ? - this._getImagePlaneGeo(transform, node) : - this._getFlatImagePlaneGeo(transform); - return new THREE.Mesh(geometry, material); + TouchZoomHandler.prototype._disable = function () { + this._activeSubscription.unsubscribe(); + this._preventDefaultSubscription.unsubscribe(); + this._zoomSubscription.unsubscribe(); + this._preventDefaultSubscription = null; + this._zoomSubscription = null; }; - ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) { - var gpano = transform.gpano; - var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2; - var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels; - var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels; - var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2; - var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels; - var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels; - var materialParameters = { - depthWrite: false, - fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment, - side: THREE.DoubleSide, - transparent: true, - uniforms: { - opacity: { - type: "f", - value: 1, - }, - phiLength: { - type: "f", - value: phiLength, - }, - phiShift: { - type: "f", - value: phiShift, - }, - projectorMat: { - type: "m4", - value: transform.rt, - }, - projectorTex: { - type: "t", - value: texture, - }, - thetaLength: { - type: "f", - value: thetaLength, - }, - thetaShift: { - type: "f", - value: thetaShift, - }, - }, - vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex, - }; - return materialParameters; + TouchZoomHandler.prototype._getConfiguration = function (enable) { + return { touchZoom: enable }; }; - ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) { - var materialParameters = { - depthWrite: false, - fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment, - side: THREE.DoubleSide, - transparent: true, - uniforms: { - bbox: { - type: "v4", - value: new THREE.Vector4(0, 0, 1, 1), - }, - opacity: { - type: "f", - value: 1, - }, - projectorMat: { - type: "m4", - value: transform.projectorMatrix(), - }, - projectorTex: { - type: "t", - value: texture, - }, - }, - vertexShader: Component_1.ImagePlaneShaders.perspective.vertex, - }; - return materialParameters; + return TouchZoomHandler; +}(Component_1.HandlerBase)); +exports.TouchZoomHandler = TouchZoomHandler; +exports.default = TouchZoomHandler; + +},{"../../Component":290,"rxjs/Observable":29}],343:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Popup_1 = require("./popup/Popup"); +exports.Popup = Popup_1.Popup; +var PopupComponent_1 = require("./PopupComponent"); +exports.PopupComponent = PopupComponent_1.PopupComponent; + +},{"./PopupComponent":344,"./popup/Popup":345}],344:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - ImagePlaneFactory.prototype._createTexture = function (image) { - var texture = new THREE.Texture(image); - texture.minFilter = THREE.LinearFilter; - texture.needsUpdate = true; - return texture; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Subject_1 = require("rxjs/Subject"); +var Component_1 = require("../../Component"); +var Utils_1 = require("../../Utils"); +/** + * @class PopupComponent + * + * @classdesc Component for showing HTML popup objects. + * + * The `add` method is used for adding new popups. Popups are removed by reference. + * + * It is not possible to update popups in the set by updating any properties + * directly on the popup object. Popups need to be replaced by + * removing them and creating new ones with relevant changed properties and + * adding those instead. + * + * Popups are only relevant to a single image because they are based on + * 2D basic image coordinates. Popups related to a certain image should + * be removed when the viewer is moved to another node. + * + * To retrive and use the popup component + * + * @example + * ``` + * var viewer = new Mapillary.Viewer( + * "", + * "", + * "", + * { component: { popup: true } }); + * + * var popupComponent = viewer.getComponent("popup"); + * ``` + */ +var PopupComponent = /** @class */ (function (_super) { + __extends(PopupComponent, _super); + function PopupComponent(name, container, navigator, dom) { + var _this = _super.call(this, name, container, navigator) || this; + _this._dom = !!dom ? dom : new Utils_1.DOM(); + _this._popups = []; + _this._added$ = new Subject_1.Subject(); + _this._popups$ = new Subject_1.Subject(); + return _this; + } + /** + * Add popups to the popups set. + * + * @description Adding a new popup never replaces an old one + * because they are stored by reference. Adding an already + * existing popup has no effect. + * + * @param {Array} popups - Popups to add. + * + * @example ```popupComponent.add([popup1, popup2]);``` + */ + PopupComponent.prototype.add = function (popups) { + for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) { + var popup = popups_1[_i]; + if (this._popups.indexOf(popup) !== -1) { + continue; + } + this._popups.push(popup); + if (this._activated) { + popup.setParentContainer(this._popupContainer); + } + } + this._added$.next(popups); + this._popups$.next(this._popups); }; - ImagePlaneFactory.prototype._useMesh = function (transform, node) { - return node.mesh.vertices.length && - transform.scale > 1e-2 && - transform.scale < 50; + /** + * Returns an array of all popups. + * + * @example ```var popups = popupComponent.getAll();``` + */ + PopupComponent.prototype.getAll = function () { + return this._popups.slice(); }; - ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) { - var t = new THREE.Matrix4().getInverse(transform.srt); - // push everything at least 5 meters in front of the camera - var minZ = 5.0 * transform.scale; - var maxZ = this._imageSphereRadius * transform.scale; - var vertices = node.mesh.vertices; - var numVertices = vertices.length / 3; - var positions = new Float32Array(vertices.length); - for (var i = 0; i < numVertices; ++i) { - var index = 3 * i; - var x = vertices[index + 0]; - var y = vertices[index + 1]; - var z = vertices[index + 2]; - var l = Math.sqrt(x * x + y * y + z * z); - var boundedL = Math.max(minZ, Math.min(l, maxZ)); - var factor = boundedL / l; - var p = new THREE.Vector3(x * factor, y * factor, z * factor); - p.applyMatrix4(t); - positions[index + 0] = p.x; - positions[index + 1] = p.y; - positions[index + 2] = p.z; - } - var faces = node.mesh.faces; - var indices = new Uint16Array(faces.length); - for (var i = 0; i < faces.length; ++i) { - indices[i] = faces[i]; + /** + * Remove popups based on reference from the popup set. + * + * @param {Array} popups - Popups to remove. + * + * @example ```popupComponent.remove([popup1, popup2]);``` + */ + PopupComponent.prototype.remove = function (popups) { + for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) { + var popup = popups_2[_i]; + this._remove(popup); } - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); - geometry.setIndex(new THREE.BufferAttribute(indices, 1)); - return geometry; + this._popups$.next(this._popups); }; - ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) { - var t = new THREE.Matrix4().getInverse(transform.srt); - // push everything at least 5 meters in front of the camera - var minZ = 5.0 * transform.scale; - var maxZ = this._imagePlaneDepth * transform.scale; - var vertices = node.mesh.vertices; - var numVertices = vertices.length / 3; - var positions = new Float32Array(vertices.length); - for (var i = 0; i < numVertices; ++i) { - var index = 3 * i; - var x = vertices[index + 0]; - var y = vertices[index + 1]; - var z = vertices[index + 2]; - var boundedZ = Math.max(minZ, Math.min(z, maxZ)); - var factor = boundedZ / z; - var p = new THREE.Vector3(x * factor, y * factor, boundedZ); - p.applyMatrix4(t); - positions[index + 0] = p.x; - positions[index + 1] = p.y; - positions[index + 2] = p.z; + /** + * Remove all popups from the popup set. + * + * @example ```popupComponent.removeAll();``` + */ + PopupComponent.prototype.removeAll = function () { + for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) { + var popup = _a[_i]; + this._remove(popup); } - var faces = node.mesh.faces; - var indices = new Uint16Array(faces.length); - for (var i = 0; i < faces.length; ++i) { - indices[i] = faces[i]; + this._popups$.next(this._popups); + }; + PopupComponent.prototype._activate = function () { + var _this = this; + this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element); + for (var _i = 0, _a = this._popups; _i < _a.length; _i++) { + var popup = _a[_i]; + popup.setParentContainer(this._popupContainer); + } + this._updateAllSubscription = Observable_1.Observable + .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$) + .subscribe(function (_a) { + var renderCamera = _a[0], size = _a[1], transform = _a[2]; + for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) { + var popup = _b[_i]; + popup.update(renderCamera, size, transform); + } + }); + var changed$ = this._popups$ + .startWith(this._popups) + .switchMap(function (popups) { + return Observable_1.Observable + .from(popups) + .mergeMap(function (popup) { + return popup.changed$; + }); + }) + .map(function (popup) { + return [popup]; + }); + this._updateAddedChangedSubscription = this._added$ + .merge(changed$) + .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$) + .subscribe(function (_a) { + var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3]; + for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) { + var popup = popups_3[_i]; + popup.update(renderCamera, size, transform); + } + }); + }; + PopupComponent.prototype._deactivate = function () { + this._updateAllSubscription.unsubscribe(); + this._updateAddedChangedSubscription.unsubscribe(); + for (var _i = 0, _a = this._popups; _i < _a.length; _i++) { + var popup = _a[_i]; + popup.remove(); } - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); - geometry.setIndex(new THREE.BufferAttribute(indices, 1)); - return geometry; + this._container.element.removeChild(this._popupContainer); + delete this._popupContainer; }; - ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) { - var gpano = transform.gpano; - var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels; - var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels; - var thetaStart = Math.PI * - (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) / - gpano.FullPanoHeightPixels; - var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels; - var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength); - geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt)); - return geometry; + PopupComponent.prototype._getDefaultConfiguration = function () { + return {}; }; - ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) { - var width = transform.width; - var height = transform.height; - var size = Math.max(width, height); - var dx = width / 2.0 / size; - var dy = height / 2.0 / size; - var vertices = []; - vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth)); - vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth)); - vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth)); - vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth)); - var positions = new Float32Array(12); - for (var i = 0; i < vertices.length; i++) { - var index = 3 * i; - positions[index + 0] = vertices[i][0]; - positions[index + 1] = vertices[i][1]; - positions[index + 2] = vertices[i][2]; + PopupComponent.prototype._remove = function (popup) { + var index = this._popups.indexOf(popup); + if (index === -1) { + return; + } + var removed = this._popups.splice(index, 1)[0]; + if (this._activated) { + removed.remove(); } - var indices = new Uint16Array(6); - indices[0] = 0; - indices[1] = 1; - indices[2] = 3; - indices[3] = 1; - indices[4] = 2; - indices[5] = 3; - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); - geometry.setIndex(new THREE.BufferAttribute(indices, 1)); - return geometry; }; - return ImagePlaneFactory; -}()); -exports.ImagePlaneFactory = ImagePlaneFactory; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ImagePlaneFactory; + PopupComponent.componentName = "popup"; + return PopupComponent; +}(Component_1.Component)); +exports.PopupComponent = PopupComponent; +Component_1.ComponentService.register(PopupComponent); +exports.default = PopupComponent; -},{"../../Component":207,"three":157}],238:[function(require,module,exports){ -/// +},{"../../Component":290,"../../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34}],345:[function(require,module,exports){ "use strict"; -var Component_1 = require("../../Component"); -var Geo_1 = require("../../Geo"); -var ImagePlaneGLRenderer = (function () { - function ImagePlaneGLRenderer() { - this._imagePlaneFactory = new Component_1.ImagePlaneFactory(); - this._imagePlaneScene = new Component_1.ImagePlaneScene(); - this._alpha = 0; - this._alphaOld = 0; - this._fadeOutSpeed = 0.05; - this._lastCamera = new Geo_1.Camera(); - this._epsilon = 0.000001; - this._currentKey = null; - this._previousKey = null; - this._frameId = 0; - this._needsRender = false; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var Subject_1 = require("rxjs/Subject"); +var Geo_1 = require("../../../Geo"); +var Utils_1 = require("../../../Utils"); +var Viewer_1 = require("../../../Viewer"); +/** + * @class Popup + * + * @classdesc Popup instance for rendering custom HTML content + * on top of images. Popups are based on 2D basic image coordinates + * (see the {@link Viewer} class documentation for more information about coordinate + * systems) and a certain popup is therefore only relevant to a single image. + * Popups related to a certain image should be removed when moving + * to another image. + * + * A popup must have both its content and its point or rect set to be + * rendered. Popup options can not be updated after creation but the + * basic point or rect as well as its content can be changed by calling + * the appropriate methods. + * + * To create and add one `Popup` with default configuration + * (tooltip visuals and automatic float) and one with specific options + * use + * + * @example + * ``` + * var defaultSpan = document.createElement('span'); + * defaultSpan.innerHTML = 'hello default'; + * + * var defaultPopup = new Mapillary.PopupComponent.Popup(); + * defaultPopup.setDOMContent(defaultSpan); + * defaultPopup.setBasicPoint([0.3, 0.3]); + * + * var cleanSpan = document.createElement('span'); + * cleanSpan.innerHTML = 'hello clean'; + * + * var cleanPopup = new Mapillary.PopupComponent.Popup({ + * clean: true, + * float: Mapillary.Alignment.Top, + * offset: 10, + * opacity: 0.7, + * }); + * + * cleanPopup.setDOMContent(cleanSpan); + * cleanPopup.setBasicPoint([0.6, 0.6]); + * + * popupComponent.add([defaultPopup, cleanPopup]); + * ``` + * + * @description Implementation of API methods and API documentation inspired + * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js + */ +var Popup = /** @class */ (function () { + function Popup(options, viewportCoords, dom) { + this._options = {}; + if (!!options) { + this._options.capturePointer = options.capturePointer == null ? true : options.capturePointer; + this._options.clean = options.clean; + this._options.float = options.float; + this._options.offset = options.offset; + this._options.opacity = options.opacity; + this._options.position = options.position; + } + this._dom = !!dom ? dom : new Utils_1.DOM(); + this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords(); + this._notifyChanged$ = new Subject_1.Subject(); } - Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", { - get: function () { - return this._frameId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", { + Object.defineProperty(Popup.prototype, "changed$", { + /** + * @ignore + * + * @description Internal observable used by the component to + * render the popup when its position or content has changed. + */ get: function () { - return this._needsRender; + return this._notifyChanged$; }, enumerable: true, configurable: true }); - ImagePlaneGLRenderer.prototype.updateFrame = function (frame) { - this._updateFrameId(frame.id); - this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender; - this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender; - this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender; - }; - ImagePlaneGLRenderer.prototype.updateTexture = function (image, node) { - if (this._currentKey !== node.key) { - return; - } - this._needsRender = true; - for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) { - var plane = _a[_i]; - var material = plane.material; - var texture = material.uniforms.projectorTex.value; - texture.image = image; - texture.needsUpdate = true; - } - }; - ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) { - var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha; - for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) { - var plane = _a[_i]; - plane.material.uniforms.opacity.value = planeAlpha; + /** + * @ignore + * + * @description Internal method used by the component to + * remove all references to the popup. + */ + Popup.prototype.remove = function () { + if (this._content && this._content.parentNode) { + this._content.parentNode.removeChild(this._content); } - for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) { - var plane = _c[_b]; - plane.material.uniforms.opacity.value = this._alphaOld; + if (this._container) { + this._container.parentNode.removeChild(this._container); + delete this._container; } - renderer.render(this._imagePlaneScene.scene, perspectiveCamera); - renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera); - for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) { - var plane = _e[_d]; - plane.material.uniforms.opacity.value = this._alpha; + if (this._parentContainer) { + delete this._parentContainer; } - renderer.render(this._imagePlaneScene.scene, perspectiveCamera); }; - ImagePlaneGLRenderer.prototype.clearNeedsRender = function () { - this._needsRender = false; + /** + * Sets a 2D basic image coordinates point to the popup's anchor, and + * moves the popup to it. + * + * @description Overwrites any previously set point or rect. + * + * @param {Array} basicPoint - Point in 2D basic image coordinates. + * + * @example + * ``` + * var popup = new Mapillary.PopupComponent.Popup(); + * popup.setText('hello image'); + * popup.setBasicPoint([0.3, 0.3]); + * + * popupComponent.add([popup]); + * ``` + */ + Popup.prototype.setBasicPoint = function (basicPoint) { + this._point = basicPoint.slice(); + this._rect = null; + this._notifyChanged$.next(this); }; - ImagePlaneGLRenderer.prototype.dispose = function () { - this._imagePlaneScene.clear(); + /** + * Sets a 2D basic image coordinates rect to the popup's anchor, and + * moves the popup to it. + * + * @description Overwrites any previously set point or rect. + * + * @param {Array} basicRect - Rect in 2D basic image + * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) . + * + * @example + * ``` + * var popup = new Mapillary.PopupComponent.Popup(); + * popup.setText('hello image'); + * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]); + * + * popupComponent.add([popup]); + * ``` + */ + Popup.prototype.setBasicRect = function (basicRect) { + this._rect = basicRect.slice(); + this._point = null; + this._notifyChanged$.next(this); }; - ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) { - this._frameId = frameId; + /** + * Sets the popup's content to the element provided as a DOM node. + * + * @param {Node} htmlNode - A DOM node to be used as content for the popup. + * + * @example + * ``` + * var div = document.createElement('div'); + * div.innerHTML = 'hello image'; + * + * var popup = new Mapillary.PopupComponent.Popup(); + * popup.setDOMContent(div); + * popup.setBasicPoint([0.3, 0.3]); + * + * popupComponent.add([popup]); + * ``` + */ + Popup.prototype.setDOMContent = function (htmlNode) { + if (this._content && this._content.parentNode) { + this._content.parentNode.removeChild(this._content); + } + var className = "mapillaryjs-popup-content" + + (this._options.clean === true ? "-clean" : "") + + (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : ""); + this._content = this._dom.createElement("div", className, this._container); + this._content.appendChild(htmlNode); + this._notifyChanged$.next(this); }; - ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) { - if (alpha === this._alpha) { - return false; + /** + * Sets the popup's content to the HTML provided as a string. + * + * @description This method does not perform HTML filtering or sanitization, + * and must be used only with trusted content. Consider Popup#setText if the + * content is an untrusted text string. + * + * @param {string} html - A string representing HTML content for the popup. + * + * @example + * ``` + * var popup = new Mapillary.PopupComponent.Popup(); + * popup.setHTML('
hello image
'); + * popup.setBasicPoint([0.3, 0.3]); + * + * popupComponent.add([popup]); + * ``` + */ + Popup.prototype.setHTML = function (html) { + var frag = this._dom.document.createDocumentFragment(); + var temp = this._dom.createElement("body"); + var child; + temp.innerHTML = html; + while (true) { + child = temp.firstChild; + if (!child) { + break; + } + frag.appendChild(child); } - this._alpha = alpha; - return true; + this.setDOMContent(frag); }; - ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) { - if (alpha < 1 || this._alphaOld === 0) { - return false; + /** + * Sets the popup's content to a string of text. + * + * @description This function creates a Text node in the DOM, so it cannot insert raw HTML. + * Use this method for security against XSS if the popup content is user-provided. + * + * @param {string} text - Textual content for the popup. + * + * @example + * ``` + * var popup = new Mapillary.PopupComponent.Popup(); + * popup.setText('hello image'); + * popup.setBasicPoint([0.3, 0.3]); + * + * popupComponent.add([popup]); + * ``` + */ + Popup.prototype.setText = function (text) { + this.setDOMContent(this._dom.document.createTextNode(text)); + }; + /** + * @ignore + * + * @description Internal method for attaching the popup to + * its parent container so that it is rendered in the DOM tree. + */ + Popup.prototype.setParentContainer = function (parentContainer) { + this._parentContainer = parentContainer; + }; + /** + * @ignore + * + * @description Internal method for updating the rendered + * position of the popup called by the popup component. + */ + Popup.prototype.update = function (renderCamera, size, transform) { + if (!this._parentContainer || !this._content) { + return; + } + if (!this._point && !this._rect) { + return; } - this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed); - return true; - }; - ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) { - if (state.currentNode == null || state.currentNode.key === this._currentKey) { - return false; + if (!this._container) { + this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer); + var showTip = this._options.clean !== true && + this._options.float !== Viewer_1.Alignment.Center; + if (showTip) { + var tipClassName = "mapillaryjs-popup-tip" + + (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : ""); + this._tip = this._dom.createElement("div", tipClassName, this._container); + this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip); + } + this._container.appendChild(this._content); + this._parentContainer.appendChild(this._container); + if (this._options.opacity != null) { + this._container.style.opacity = this._options.opacity.toString(); + } + } + var pointPixel = null; + var position = this._alignmentToPopupAligment(this._options.position); + var float = this._alignmentToPopupAligment(this._options.float); + var classList = this._container.classList; + if (this._point != null) { + pointPixel = + this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective); } - this._previousKey = state.previousNode != null ? state.previousNode.key : null; - if (this._previousKey != null) { - if (this._previousKey !== this._currentKey) { - var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform); - this._imagePlaneScene.updateImagePlanes([previousMesh]); + else { + var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"]; + var appliedPosition = null; + for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) { + var alignment = alignments_1[_i]; + if (classList.contains("mapillaryjs-popup-float-" + alignment)) { + appliedPosition = alignment; + break; + } + } + _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1]; + if (!float) { + float = position; } } - this._currentKey = state.currentNode.key; - var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform); - this._imagePlaneScene.updateImagePlanes([currentMesh]); - this._alphaOld = 1; - return true; - }; - return ImagePlaneGLRenderer; -}()); -exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ImagePlaneGLRenderer; - -},{"../../Component":207,"../../Geo":210}],239:[function(require,module,exports){ -/// -"use strict"; -var THREE = require("three"); -var ImagePlaneScene = (function () { - function ImagePlaneScene() { - this.scene = new THREE.Scene(); - this.sceneOld = new THREE.Scene(); - this.imagePlanes = []; - this.imagePlanesOld = []; - } - ImagePlaneScene.prototype.updateImagePlanes = function (planes) { - this._dispose(this.imagePlanesOld, this.sceneOld); - for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) { - var plane = _a[_i]; - this.scene.remove(plane); - this.sceneOld.add(plane); + if (pointPixel == null) { + this._container.style.visibility = "hidden"; + return; } - for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) { - var plane = planes_1[_b]; - this.scene.add(plane); + this._container.style.visibility = "visible"; + if (!float) { + var width = this._container.offsetWidth; + var height = this._container.offsetHeight; + var floats = this._pixelToFloats(pointPixel, size, width, height); + float = floats.length === 0 ? "top" : floats.join("-"); + } + var offset = this._normalizeOffset(this._options.offset); + pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]]; + pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])]; + var floatTranslate = { + "bottom": "translate(-50%,0)", + "bottom-left": "translate(-100%,0)", + "bottom-right": "translate(0,0)", + "center": "translate(-50%,-50%)", + "left": "translate(-100%,-50%)", + "right": "translate(0,-50%)", + "top": "translate(-50%,-100%)", + "top-left": "translate(-100%,-100%)", + "top-right": "translate(0,-100%)", + }; + for (var key in floatTranslate) { + if (!floatTranslate.hasOwnProperty(key)) { + continue; + } + classList.remove("mapillaryjs-popup-float-" + key); + } + classList.add("mapillaryjs-popup-float-" + float); + this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)"; + var _a; + }; + Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) { + if (!position) { + var width = this._container.offsetWidth; + var height = this._container.offsetHeight; + var floatOffsets = { + "bottom": [0, height / 2], + "bottom-left": [-width / 2, height / 2], + "bottom-right": [width / 2, height / 2], + "left": [-width / 2, 0], + "right": [width / 2, 0], + "top": [0, -height / 2], + "top-left": [-width / 2, -height / 2], + "top-right": [width / 2, -height / 2], + }; + var automaticPositions = ["top", "bottom", "left", "right"]; + var largestVisibleArea = [0, null, null]; + for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) { + var automaticPosition = automaticPositions_1[_i]; + var autoPointBasic = this._pointFromRectPosition(rect, automaticPosition); + var autoPointPixel = this._viewportCoords.basicToCanvasSafe(autoPointBasic[0], autoPointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective); + if (autoPointPixel == null) { + continue; + } + var floatOffset = floatOffsets[automaticPosition]; + var offsetedPosition = [autoPointPixel[0] + floatOffset[0], autoPointPixel[1] + floatOffset[1]]; + var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7; + var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff)); + if (floats.length === 0 && + autoPointPixel[0] > 0 && + autoPointPixel[0] < size.width && + autoPointPixel[1] > 0 && + autoPointPixel[1] < size.height) { + return [autoPointPixel, automaticPosition]; + } + var minX = Math.max(offsetedPosition[0] - width / 2, 0); + var maxX = Math.min(offsetedPosition[0] + width / 2, size.width); + var minY = Math.max(offsetedPosition[1] - height / 2, 0); + var maxY = Math.min(offsetedPosition[1] + height / 2, size.height); + var visibleX = Math.max(0, maxX - minX); + var visibleY = Math.max(0, maxY - minY); + var visibleArea = staticCoeff * visibleX * visibleY; + if (visibleArea > largestVisibleArea[0]) { + largestVisibleArea[0] = visibleArea; + largestVisibleArea[1] = autoPointPixel; + largestVisibleArea[2] = automaticPosition; + } + } + if (largestVisibleArea[0] > 0) { + return [largestVisibleArea[1], largestVisibleArea[2]]; + } + } + var pointBasic = this._pointFromRectPosition(rect, position); + var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective); + return [pointPixel, position != null ? position : "top"]; + }; + Popup.prototype._alignmentToPopupAligment = function (float) { + switch (float) { + case Viewer_1.Alignment.Bottom: + return "bottom"; + case Viewer_1.Alignment.BottomLeft: + return "bottom-left"; + case Viewer_1.Alignment.BottomRight: + return "bottom-right"; + case Viewer_1.Alignment.Center: + return "center"; + case Viewer_1.Alignment.Left: + return "left"; + case Viewer_1.Alignment.Right: + return "right"; + case Viewer_1.Alignment.Top: + return "top"; + case Viewer_1.Alignment.TopLeft: + return "top-left"; + case Viewer_1.Alignment.TopRight: + return "top-right"; + default: + return null; } - this.imagePlanesOld = this.imagePlanes; - this.imagePlanes = planes; }; - ImagePlaneScene.prototype.addImagePlanes = function (planes) { - for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) { - var plane = planes_2[_i]; - this.scene.add(plane); - this.imagePlanes.push(plane); + Popup.prototype._normalizeOffset = function (offset) { + if (offset == null) { + return this._normalizeOffset(0); } - }; - ImagePlaneScene.prototype.addImagePlanesOld = function (planes) { - for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) { - var plane = planes_3[_i]; - this.sceneOld.add(plane); - this.imagePlanesOld.push(plane); + if (typeof offset === "number") { + // input specifies a radius + var sideOffset = offset; + var sign = sideOffset >= 0 ? 1 : -1; + var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2))); + return { + "bottom": [0, sideOffset], + "bottom-left": [-cornerOffset, cornerOffset], + "bottom-right": [cornerOffset, cornerOffset], + "center": [0, 0], + "left": [-sideOffset, 0], + "right": [sideOffset, 0], + "top": [0, -sideOffset], + "top-left": [-cornerOffset, -cornerOffset], + "top-right": [cornerOffset, -cornerOffset], + }; + } + else { + // input specifes a value for each position + return { + "bottom": offset.bottom || [0, 0], + "bottom-left": offset.bottomLeft || [0, 0], + "bottom-right": offset.bottomRight || [0, 0], + "center": offset.center || [0, 0], + "left": offset.left || [0, 0], + "right": offset.right || [0, 0], + "top": offset.top || [0, 0], + "top-left": offset.topLeft || [0, 0], + "top-right": offset.topRight || [0, 0], + }; } }; - ImagePlaneScene.prototype.setImagePlanes = function (planes) { - this._clear(); - this.addImagePlanes(planes); - }; - ImagePlaneScene.prototype.setImagePlanesOld = function (planes) { - this._clearOld(); - this.addImagePlanesOld(planes); - }; - ImagePlaneScene.prototype.clear = function () { - this._clear(); - this._clearOld(); - }; - ImagePlaneScene.prototype._clear = function () { - this._dispose(this.imagePlanes, this.scene); - this.imagePlanes.length = 0; - }; - ImagePlaneScene.prototype._clearOld = function () { - this._dispose(this.imagePlanesOld, this.sceneOld); - this.imagePlanesOld.length = 0; + Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) { + var floats = []; + if (pointPixel[1] < height) { + floats.push("bottom"); + } + else if (pointPixel[1] > size.height - height) { + floats.push("top"); + } + if (pointPixel[0] < width / 2) { + floats.push("right"); + } + else if (pointPixel[0] > size.width - width / 2) { + floats.push("left"); + } + return floats; }; - ImagePlaneScene.prototype._dispose = function (planes, scene) { - for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) { - var plane = planes_4[_i]; - scene.remove(plane); - plane.geometry.dispose(); - plane.material.dispose(); - var texture = plane.material.uniforms.projectorTex.value; - if (texture != null) { - texture.dispose(); - } + Popup.prototype._pointFromRectPosition = function (rect, position) { + var x0 = rect[0]; + var x1 = rect[0] < rect[2] ? rect[2] : rect[2] + 1; + var y0 = rect[1]; + var y1 = rect[3]; + switch (position) { + case "bottom": + return [(x0 + x1) / 2, y1]; + case "bottom-left": + return [x0, y1]; + case "bottom-right": + return [x1, y1]; + case "center": + return [(x0 + x1) / 2, (y0 + y1) / 2]; + case "left": + return [x0, (y0 + y1) / 2]; + case "right": + return [x1, (y0 + y1) / 2]; + case "top": + return [(x0 + x1) / 2, y0]; + case "top-left": + return [x0, y0]; + case "top-right": + return [x1, y0]; + default: + return [(x0 + x1) / 2, y1]; } }; - return ImagePlaneScene; + return Popup; }()); -exports.ImagePlaneScene = ImagePlaneScene; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ImagePlaneScene; +exports.Popup = Popup; +exports.default = Popup; -},{"three":157}],240:[function(require,module,exports){ -/// +},{"../../../Geo":293,"../../../Utils":300,"../../../Viewer":301,"rxjs/Subject":34}],346:[function(require,module,exports){ "use strict"; - -var path = require("path"); -var ImagePlaneShaders = (function () { - function ImagePlaneShaders() { - } - ImagePlaneShaders.equirectangular = { - fragment: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vec3 b = normalize(vRstq.xyz);\n float lat = -asin(b.y);\n float lon = atan(b.x, b.z);\n float x = (lon - phiShift) / phiLength + 0.5;\n float y = (lat - thetaShift) / thetaLength + 0.5;\n vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n gl_FragColor = baseColor;\n}", - vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}", - }; - ImagePlaneShaders.perspective = { - fragment: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform vec4 bbox;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n float x = vRstq.x / vRstq.w;\n float y = vRstq.y / vRstq.w;\n\n vec4 baseColor;\n if (x > bbox[0] && y > bbox[1] && x < bbox[2] && y < bbox[3]) {\n baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n } else {\n baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n\n gl_FragColor = baseColor;\n}", - vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}", - }; - return ImagePlaneShaders; -}()); -exports.ImagePlaneShaders = ImagePlaneShaders; - -},{"path":21}],241:[function(require,module,exports){ /// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/observable/fromEvent"); -require("rxjs/add/observable/of"); -require("rxjs/add/observable/zip"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/first"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/merge"); -require("rxjs/add/operator/mergeMap"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/switchMap"); -require("rxjs/add/operator/withLatestFrom"); -require("rxjs/add/operator/zip"); -var Graph_1 = require("../../Graph"); -var State_1 = require("../../State"); -var Render_1 = require("../../Render"); -var Utils_1 = require("../../Utils"); var Component_1 = require("../../Component"); -var SliderState = (function () { - function SliderState() { - this._imagePlaneFactory = new Component_1.ImagePlaneFactory(); - this._imagePlaneScene = new Component_1.ImagePlaneScene(); - this._currentKey = null; - this._previousKey = null; - this._currentPano = false; - this._frameId = 0; - this._glNeedsRender = false; - this._domNeedsRender = true; - this._motionless = false; - this._curtain = 1; +var Edge_1 = require("../../Edge"); +var Graph_1 = require("../../Graph"); +/** + * @class SequenceComponent + * @classdesc Component showing navigation arrows for sequence directions + * as well as playing button. Exposes an API to start and stop play. + */ +var SequenceComponent = /** @class */ (function (_super) { + __extends(SequenceComponent, _super); + function SequenceComponent(name, container, navigator, renderer, scheduler) { + var _this = _super.call(this, name, container, navigator) || this; + _this._sequenceDOMRenderer = !!renderer ? renderer : new Component_1.SequenceDOMRenderer(container); + _this._scheduler = scheduler; + _this._containerWidth$ = new Subject_1.Subject(); + _this._hoveredKeySubject$ = new Subject_1.Subject(); + _this._hoveredKey$ = _this._hoveredKeySubject$.share(); + _this._navigator.playService.playing$ + .skip(1) + .withLatestFrom(_this._configuration$) + .subscribe(function (_a) { + var playing = _a[0], configuration = _a[1]; + _this.fire(SequenceComponent.playingchanged, playing); + if (playing === configuration.playing) { + return; + } + if (playing) { + _this.play(); + } + else { + _this.stop(); + } + }); + _this._navigator.playService.direction$ + .skip(1) + .withLatestFrom(_this._configuration$) + .subscribe(function (_a) { + var direction = _a[0], configuration = _a[1]; + if (direction !== configuration.direction) { + _this.setDirection(direction); + } + }); + return _this; } - Object.defineProperty(SliderState.prototype, "frameId", { - get: function () { - return this._frameId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SliderState.prototype, "curtain", { - get: function () { - return this._curtain; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SliderState.prototype, "glNeedsRender", { - get: function () { - return this._glNeedsRender; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SliderState.prototype, "domNeedsRender", { - get: function () { - return this._domNeedsRender; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SliderState.prototype, "sliderVisible", { - get: function () { - return this._sliderVisible; - }, - set: function (value) { - this._sliderVisible = value; - this._domNeedsRender = true; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SliderState.prototype, "disabled", { + Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", { + /** + * Get hovered key observable. + * + * @description An observable emitting the key of the node for the direction + * arrow that is being hovered. When the mouse leaves a direction arrow null + * is emitted. + * + * @returns {Observable} + */ get: function () { - return this._currentKey == null || - this._previousKey == null || - this._motionless || - this._currentPano; + return this._hoveredKey$; }, enumerable: true, configurable: true }); - SliderState.prototype.update = function (frame) { - this._updateFrameId(frame.id); - var needsRender = this._updateImagePlanes(frame.state); - needsRender = this._updateCurtain(frame.state.alpha) || needsRender; - this._glNeedsRender = needsRender || this._glNeedsRender; - this._domNeedsRender = needsRender || this._domNeedsRender; - }; - SliderState.prototype.updateTexture = function (image, node) { - var imagePlanes = node.key === this._currentKey ? - this._imagePlaneScene.imagePlanes : - node.key === this._previousKey ? - this._imagePlaneScene.imagePlanesOld : - []; - if (imagePlanes.length === 0) { - return; - } - this._glNeedsRender = true; - for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) { - var plane = imagePlanes_1[_i]; - var material = plane.material; - var texture = material.uniforms.projectorTex.value; - texture.image = image; - texture.needsUpdate = true; - } - }; - SliderState.prototype.render = function (perspectiveCamera, renderer) { - if (!this.disabled) { - renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera); - } - renderer.render(this._imagePlaneScene.scene, perspectiveCamera); - }; - SliderState.prototype.dispose = function () { - this._imagePlaneScene.clear(); - }; - SliderState.prototype.clearGLNeedsRender = function () { - this._glNeedsRender = false; - }; - SliderState.prototype.clearDomNeedsRender = function () { - this._domNeedsRender = false; - }; - SliderState.prototype._updateFrameId = function (frameId) { - this._frameId = frameId; - }; - SliderState.prototype._updateImagePlanes = function (state) { - if (state.currentNode == null) { - return; - } - var needsRender = false; - if (state.previousNode != null && this._previousKey !== state.previousNode.key) { - needsRender = true; - this._previousKey = state.previousNode.key; - this._motionless = state.motionless; - this._imagePlaneScene.setImagePlanesOld([ - this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform), - ]); - } - if (this._currentKey !== state.currentNode.key) { - needsRender = true; - this._currentKey = state.currentNode.key; - this._currentPano = state.currentNode.pano; - this._motionless = state.motionless; - this._imagePlaneScene.setImagePlanes([ - this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform), - ]); - if (!this.disabled) { - this._updateBbox(); - } - } - return needsRender; + /** + * Start playing. + * + * @fires PlayerComponent#playingchanged + */ + SequenceComponent.prototype.play = function () { + this.configure({ playing: true }); }; - SliderState.prototype._updateCurtain = function (alpha) { - if (this.disabled || - Math.abs(this._curtain - alpha) < 0.001) { - return false; - } - this._curtain = alpha; - this._updateBbox(); - return true; + /** + * Stop playing. + * + * @fires PlayerComponent#playingchanged + */ + SequenceComponent.prototype.stop = function () { + this.configure({ playing: false }); }; - SliderState.prototype._updateBbox = function () { - for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) { - var plane = _a[_i]; - var shaderMaterial = plane.material; - var bbox = shaderMaterial.uniforms.bbox.value; - bbox.z = this._curtain; - } + /** + * Set the direction to follow when playing. + * + * @param {EdgeDirection} direction - The direction that will be followed when playing. + */ + SequenceComponent.prototype.setDirection = function (direction) { + this.configure({ direction: direction }); }; - return SliderState; -}()); -var SliderComponent = (function (_super) { - __extends(SliderComponent, _super); /** - * Create a new slider component instance. - * @class SliderComponent - */ - function SliderComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._sliderStateOperation$ = new Subject_1.Subject(); - this._sliderStateCreator$ = new Subject_1.Subject(); - this._sliderStateDisposer$ = new Subject_1.Subject(); - this._sliderState$ = this._sliderStateOperation$ - .scan(function (sliderState, operation) { - return operation(sliderState); - }, null) - .filter(function (sliderState) { - return sliderState != null; - }) - .distinctUntilChanged(undefined, function (sliderState) { - return sliderState.frameId; - }); - this._sliderStateCreator$ - .map(function () { - return function (sliderState) { - if (sliderState != null) { - throw new Error("Multiple slider states can not be created at the same time"); - } - return new SliderState(); - }; - }) - .subscribe(this._sliderStateOperation$); - this._sliderStateDisposer$ - .map(function () { - return function (sliderState) { - sliderState.dispose(); - return null; - }; - }) - .subscribe(this._sliderStateOperation$); - } + * Set highlight key. + * + * @description The arrow pointing towards the node corresponding to the + * highlight key will be highlighted. + * + * @param {string} highlightKey Key of node to be highlighted if existing. + */ + SequenceComponent.prototype.setHighlightKey = function (highlightKey) { + this.configure({ highlightKey: highlightKey }); + }; /** - * Set the image keys. + * Set max width of container element. + * + * @description Set max width of the container element holding + * the sequence navigation elements. If the min width is larger than the + * max width the min width value will be used. * - * Configures the component to show the image planes for the supplied image keys. + * The container element is automatically resized when the resize + * method on the Viewer class is called. * - * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background. + * @param {number} minWidth */ - SliderComponent.prototype.setKeys = function (keys) { - this.configure({ keys: keys }); + SequenceComponent.prototype.setMaxWidth = function (maxWidth) { + this.configure({ maxWidth: maxWidth }); }; /** - * Set the initial position. + * Set min width of container element. + * + * @description Set min width of the container element holding + * the sequence navigation elements. If the min width is larger than the + * max width the min width value will be used. * - * Configures the intial position of the slider. The inital position value will be used when the component is activated. + * The container element is automatically resized when the resize + * method on the Viewer class is called. * - * @param {number} initialPosition - Initial slider position. + * @param {number} minWidth */ - SliderComponent.prototype.setInitialPosition = function (initialPosition) { - this.configure({ initialPosition: initialPosition }); + SequenceComponent.prototype.setMinWidth = function (minWidth) { + this.configure({ minWidth: minWidth }); }; /** - * Set the value controlling if the slider is visible. + * Set the value indicating whether the sequence UI elements should be visible. * - * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not. + * @param {boolean} visible */ - SliderComponent.prototype.setSliderVisible = function (sliderVisible) { - this.configure({ sliderVisible: sliderVisible }); + SequenceComponent.prototype.setVisible = function (visible) { + this.configure({ visible: visible }); }; - SliderComponent.prototype._activate = function () { + /** @inheritdoc */ + SequenceComponent.prototype.resize = function () { var _this = this; - this._container.mouseService.preventDefaultMouseDown$.next(false); - this._container.touchService.preventDefaultTouchMove$.next(false); - Observable_1.Observable - .combineLatest(this._navigator.stateService.state$, this._configuration$) + this._configuration$ .first() - .subscribe(function (stateConfig) { - if (stateConfig[0] === State_1.State.Traversing) { - _this._navigator.stateService.wait(); - var position = stateConfig[1].initialPosition; - _this._navigator.stateService.moveTo(position != null ? position : 1); - } + .map(function (configuration) { + return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration); + }) + .subscribe(function (containerWidth) { + _this._containerWidth$.next(containerWidth); }); - this._glRenderSubscription = this._sliderState$ - .map(function (sliderState) { - var renderHash = { - name: _this._name, - render: { - frameId: sliderState.frameId, - needsRender: sliderState.glNeedsRender, - render: sliderState.render.bind(sliderState), - stage: Render_1.GLRenderStage.Background, - }, - }; - sliderState.clearGLNeedsRender(); - return renderHash; + }; + SequenceComponent.prototype._activate = function () { + var _this = this; + this._sequenceDOMRenderer.activate(); + var edgeStatus$ = this._navigator.stateService.currentNode$ + .switchMap(function (node) { + return node.sequenceEdges$; }) - .subscribe(this._container.glRenderer.render$); - this._domRenderSubscription = this._sliderState$ - .filter(function (sliderState) { - return sliderState.domNeedsRender; - }) - .map(function (sliderState) { - var sliderInput = vd.h("input.SliderControl", { - max: 1000, - min: 0, - type: "range", - value: 1000 * sliderState.curtain, - }, []); - var vNode = sliderState.disabled || !sliderState.sliderVisible ? - null : - vd.h("div.SliderWrapper", {}, [sliderInput]); - var hash = { - name: _this._name, - vnode: vNode, - }; - sliderState.clearDomNeedsRender(); - return hash; + .publishReplay(1) + .refCount(); + var sequence$ = this._navigator.stateService.currentNode$ + .distinctUntilChanged(undefined, function (node) { + return node.sequenceKey; }) - .subscribe(this._container.domRenderer.render$); - this._elementSubscription = this._container.domRenderer.element$ - .map(function (e) { - var nodeList = e.getElementsByClassName("SliderControl"); - var slider = nodeList.length > 0 ? nodeList[0] : null; - return slider; + .switchMap(function (node) { + return Observable_1.Observable + .concat(Observable_1.Observable.of(null), _this._navigator.graphService.cacheSequence$(node.sequenceKey) + .retry(3) + .catch(function (e) { + console.error("Failed to cache sequence", e); + return Observable_1.Observable.of(null); + })); }) - .filter(function (input) { - return input != null; + .startWith(null) + .publishReplay(1) + .refCount(); + this._sequenceSubscription = sequence$.subscribe(); + var rendererKey$ = this._sequenceDOMRenderer.index$ + .withLatestFrom(sequence$) + .map(function (_a) { + var index = _a[0], sequence = _a[1]; + return sequence != null ? sequence.keys[index] : null; }) - .switchMap(function (input) { - return Observable_1.Observable.fromEvent(input, "input"); + .filter(function (key) { + return !!key; }) - .map(function (e) { - return Number(e.target.value) / 1000; + .distinctUntilChanged() + .publish() + .refCount(); + this._moveSubscription = Observable_1.Observable + .merge(rendererKey$.debounceTime(100, this._scheduler), rendererKey$.auditTime(400, this._scheduler)) + .distinctUntilChanged() + .switchMap(function (key) { + return _this._navigator.moveToKey$(key) + .catch(function (e) { + return Observable_1.Observable.empty(); + }); + }) + .subscribe(); + this._setSequenceGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$ + .filter(function (changing) { + return changing; }) - .subscribe(function (curtain) { - _this._navigator.stateService.moveTo(curtain); + .subscribe(function () { + _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Sequence); }); - this._sliderStateCreator$.next(null); - this._stateSubscription = this._navigator.stateService.currentState$ - .map(function (frame) { - return function (sliderState) { - sliderState.update(frame); - return sliderState; - }; + this._setSpatialGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$ + .filter(function (changing) { + return !changing; }) - .subscribe(this._sliderStateOperation$); - this._setSliderVisibleSubscription = this._configuration$ - .map(function (configuration) { - return configuration.sliderVisible == null || configuration.sliderVisible; + .subscribe(function () { + _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Spatial); + }); + this._navigator.graphService.graphMode$ + .switchMap(function (mode) { + return mode === Graph_1.GraphMode.Spatial ? + _this._navigator.stateService.currentNode$ + .take(2) : + Observable_1.Observable.empty(); }) - .distinctUntilChanged() - .map(function (sliderVisible) { - return function (sliderState) { - sliderState.sliderVisible = sliderVisible; - return sliderState; - }; + .filter(function (node) { + return !node.spatialEdges.cached; }) - .subscribe(this._sliderStateOperation$); - this._setKeysSubscription = this._configuration$ - .filter(function (configuration) { - return configuration.keys != null; + .switchMap(function (node) { + return _this._navigator.graphService.cacheNode$(node.key) + .catch(function (e) { + return Observable_1.Observable.empty(); + }); }) - .switchMap(function (configuration) { - return Observable_1.Observable - .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground)) - .map(function (nodes) { - return { background: nodes[0], foreground: nodes[1] }; + .subscribe(); + this._stopSubscription = this._sequenceDOMRenderer.changingPositionChanged$ + .filter(function (changing) { + return changing; + }) + .subscribe(function () { + _this._navigator.playService.stop(); + }); + this._cacheSequenceNodesSubscription = Observable_1.Observable + .combineLatest(this._navigator.graphService.graphMode$, this._sequenceDOMRenderer.changingPositionChanged$ + .startWith(false) + .distinctUntilChanged()) + .withLatestFrom(this._navigator.stateService.currentNode$) + .switchMap(function (_a) { + var _b = _a[0], mode = _b[0], changing = _b[1], node = _a[1]; + return changing && mode === Graph_1.GraphMode.Sequence ? + _this._navigator.graphService.cacheSequenceNodes$(node.sequenceKey, node.key) + .retry(3) + .catch(function (error) { + console.error("Failed to cache sequence nodes.", error); + return Observable_1.Observable.empty(); + }) : + Observable_1.Observable.empty(); + }) + .subscribe(); + var position$ = sequence$ + .switchMap(function (sequence) { + if (!sequence) { + return Observable_1.Observable.of({ index: null, max: null }); + } + var firstCurrentKey = true; + return _this._sequenceDOMRenderer.changingPositionChanged$ + .startWith(false) + .distinctUntilChanged() + .switchMap(function (changingPosition) { + var skip = !changingPosition && firstCurrentKey ? 0 : 1; + firstCurrentKey = false; + return changingPosition ? + rendererKey$ : + _this._navigator.stateService.currentNode$ + .map(function (node) { + return node.key; + }) + .distinctUntilChanged() + .skip(skip); }) - .zip(_this._navigator.stateService.currentState$.first()) - .map(function (nf) { - return { nodes: nf[0], state: nf[1].state }; + .map(function (key) { + var index = sequence.keys.indexOf(key); + if (index === -1) { + return { index: null, max: null }; + } + return { index: index, max: sequence.keys.length - 1 }; }); - }) - .subscribe(function (co) { - if (co.state.currentNode != null && - co.state.previousNode != null && - co.state.currentNode.key === co.nodes.foreground.key && - co.state.previousNode.key === co.nodes.background.key) { - return; - } - if (co.state.currentNode.key === co.nodes.background.key) { - _this._navigator.stateService.setNodes([co.nodes.foreground]); - return; - } - if (co.state.currentNode.key === co.nodes.foreground.key && - co.state.trajectory.length === 1) { - _this._navigator.stateService.prependNodes([co.nodes.background]); - return; - } - _this._navigator.stateService.setNodes([co.nodes.background]); - _this._navigator.stateService.setNodes([co.nodes.foreground]); - }, function (e) { - console.log(e); }); - var previousNode$ = this._navigator.stateService.currentState$ - .map(function (frame) { - return frame.state.previousNode; + this._renderSubscription = Observable_1.Observable + .combineLatest(edgeStatus$, this._configuration$, this._containerWidth$, this._sequenceDOMRenderer.changed$.startWith(this._sequenceDOMRenderer), this._navigator.playService.speed$, position$) + .map(function (_a) { + var edgeStatus = _a[0], configuration = _a[1], containerWidth = _a[2], renderer = _a[3], speed = _a[4], position = _a[5]; + var vNode = _this._sequenceDOMRenderer + .render(edgeStatus, configuration, containerWidth, speed, position.index, position.max, _this, _this._navigator); + return { name: _this._name, vnode: vNode }; }) - .filter(function (node) { - return node != null; + .subscribe(this._container.domRenderer.render$); + this._setSpeedSubscription = this._sequenceDOMRenderer.speed$ + .subscribe(function (speed) { + _this._navigator.playService.setSpeed(speed); + }); + this._setDirectionSubscription = this._configuration$ + .map(function (configuration) { + return configuration.direction; }) - .distinctUntilChanged(undefined, function (node) { - return node.key; + .distinctUntilChanged() + .subscribe(function (direction) { + _this._navigator.playService.setDirection(direction); }); - this._nodeSubscription = Observable_1.Observable - .merge(previousNode$, this._navigator.stateService.currentNode$) - .filter(function (node) { - return node.pano ? - Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize : - Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize; + this._containerWidthSubscription = this._configuration$ + .distinctUntilChanged(function (value1, value2) { + return value1[0] === value2[0] && value1[1] === value2[1]; + }, function (configuration) { + return [configuration.minWidth, configuration.maxWidth]; }) - .mergeMap(function (node) { - return Graph_1.ImageLoader.loadThumbnail(node.key, Utils_1.Settings.maxImageSize) - .filter(function (statusObject) { - return statusObject.object != null; - }) - .first() - .map(function (statusObject) { - return statusObject.object; - }) - .zip(Observable_1.Observable.of(node), function (t, n) { - return [t, n]; - }) - .catch(function (error, caught) { - console.error("Failed to fetch high res slider image (" + node.key + ")", error); - return Observable_1.Observable.empty(); - }); + .map(function (configuration) { + return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration); }) - .map(function (imn) { - return function (sliderState) { - sliderState.updateTexture(imn[0], imn[1]); - return sliderState; - }; + .subscribe(this._containerWidth$); + this._playingSubscription = this._configuration$ + .map(function (configuration) { + return configuration.playing; }) - .subscribe(this._sliderStateOperation$); - }; - SliderComponent.prototype._deactivate = function () { - var _this = this; - this._container.mouseService.preventDefaultMouseDown$.next(true); - this._container.touchService.preventDefaultTouchMove$.next(true); - this._navigator.stateService.state$ - .first() - .subscribe(function (state) { - if (state === State_1.State.Waiting) { - _this._navigator.stateService.traverse(); + .distinctUntilChanged() + .subscribe(function (playing) { + if (playing) { + _this._navigator.playService.play(); + } + else { + _this._navigator.playService.stop(); } }); - this._sliderStateDisposer$.next(null); - this._setKeysSubscription.unsubscribe(); - this._setSliderVisibleSubscription.unsubscribe(); - this._elementSubscription.unsubscribe(); - this._stateSubscription.unsubscribe(); - this._glRenderSubscription.unsubscribe(); - this._domRenderSubscription.unsubscribe(); - this._nodeSubscription.unsubscribe(); - this.configure({ keys: null }); - }; - SliderComponent.prototype._getDefaultConfiguration = function () { - return {}; + this._hoveredKeySubscription = this._sequenceDOMRenderer.mouseEnterDirection$ + .switchMap(function (direction) { + return edgeStatus$ + .map(function (edgeStatus) { + for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { + var edge = _a[_i]; + if (edge.data.direction === direction) { + return edge.to; + } + } + return null; + }) + .takeUntil(_this._sequenceDOMRenderer.mouseLeaveDirection$) + .concat(Observable_1.Observable.of(null)); + }) + .distinctUntilChanged() + .subscribe(this._hoveredKeySubject$); }; - SliderComponent.prototype._catchCacheNode$ = function (key) { - return this._navigator.graphService.cacheNode$(key) - .catch(function (error, caught) { - console.log("Failed to cache slider node (" + key + ")", error); - return Observable_1.Observable.empty(); - }); + SequenceComponent.prototype._deactivate = function () { + this._renderSubscription.unsubscribe(); + this._playingSubscription.unsubscribe(); + this._containerWidthSubscription.unsubscribe(); + this._hoveredKeySubscription.unsubscribe(); + this._setSpeedSubscription.unsubscribe(); + this._setDirectionSubscription.unsubscribe(); + this._setSequenceGraphModeSubscription.unsubscribe(); + this._setSpatialGraphModeSubscription.unsubscribe(); + this._sequenceSubscription.unsubscribe(); + this._moveSubscription.unsubscribe(); + this._cacheSequenceNodesSubscription.unsubscribe(); + this._stopSubscription.unsubscribe(); + this._sequenceDOMRenderer.deactivate(); }; - SliderComponent.componentName = "slider"; - return SliderComponent; + SequenceComponent.prototype._getDefaultConfiguration = function () { + return { + direction: Edge_1.EdgeDirection.Next, + maxWidth: 108, + minWidth: 70, + playing: false, + visible: true, + }; + }; + /** @inheritdoc */ + SequenceComponent.componentName = "sequence"; + /** + * Event fired when playing starts or stops. + * + * @event PlayerComponent#playingchanged + * @type {boolean} Indicates whether the player is playing. + */ + SequenceComponent.playingchanged = "playingchanged"; + return SequenceComponent; }(Component_1.Component)); -exports.SliderComponent = SliderComponent; -Component_1.ComponentService.register(SliderComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SliderComponent; +exports.SequenceComponent = SequenceComponent; +Component_1.ComponentService.register(SequenceComponent); +exports.default = SequenceComponent; -},{"../../Component":207,"../../Graph":211,"../../Render":213,"../../State":214,"../../Utils":215,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/fromEvent":41,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":46,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/first":58,"rxjs/add/operator/map":60,"rxjs/add/operator/merge":61,"rxjs/add/operator/mergeMap":63,"rxjs/add/operator/scan":68,"rxjs/add/operator/switchMap":73,"rxjs/add/operator/withLatestFrom":76,"rxjs/add/operator/zip":77,"virtual-dom":163}],242:[function(require,module,exports){ +},{"../../Component":290,"../../Edge":291,"../../Graph":294,"rxjs/Observable":29,"rxjs/Subject":34}],347:[function(require,module,exports){ "use strict"; -var Marker = (function () { - function Marker(latLonAlt, markerOptions) { - this.visibleInKeys = []; - this._id = markerOptions.id; - this._latLonAlt = latLonAlt; - this._markerOptions = markerOptions; - this._type = markerOptions.type; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); +var Subject_1 = require("rxjs/Subject"); +var Component_1 = require("../../Component"); +var Edge_1 = require("../../Edge"); +var Error_1 = require("../../Error"); +var SequenceDOMRenderer = /** @class */ (function () { + function SequenceDOMRenderer(container) { + this._container = container; + this._minThresholdWidth = 320; + this._maxThresholdWidth = 1480; + this._minThresholdHeight = 240; + this._maxThresholdHeight = 820; + this._stepperDefaultWidth = 108; + this._controlsDefaultWidth = 88; + this._defaultHeight = 30; + this._expandControls = false; + this._mode = Component_1.SequenceMode.Default; + this._speed = 0.5; + this._changingSpeed = false; + this._index = null; + this._changingPosition = false; + this._mouseEnterDirection$ = new Subject_1.Subject(); + this._mouseLeaveDirection$ = new Subject_1.Subject(); + this._notifyChanged$ = new Subject_1.Subject(); + this._notifyChangingPositionChanged$ = new Subject_1.Subject(); + this._notifySpeedChanged$ = new Subject_1.Subject(); + this._notifyIndexChanged$ = new Subject_1.Subject(); } - Object.defineProperty(Marker.prototype, "id", { + Object.defineProperty(SequenceDOMRenderer.prototype, "changed$", { get: function () { - return this._id; + return this._notifyChanged$; }, enumerable: true, configurable: true }); - Object.defineProperty(Marker.prototype, "type", { + Object.defineProperty(SequenceDOMRenderer.prototype, "changingPositionChanged$", { get: function () { - return this._type; + return this._notifyChangingPositionChanged$; }, enumerable: true, configurable: true }); - Object.defineProperty(Marker.prototype, "latLonAlt", { + Object.defineProperty(SequenceDOMRenderer.prototype, "speed$", { get: function () { - return this._latLonAlt; + return this._notifySpeedChanged$; }, enumerable: true, configurable: true }); - return Marker; -}()); -exports.Marker = Marker; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Marker; - -},{}],243:[function(require,module,exports){ -/// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var _ = require("underscore"); -var THREE = require("three"); -var rbush = require("rbush"); -var Observable_1 = require("rxjs/Observable"); -var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/switchMap"); -var Component_1 = require("../../Component"); -var Render_1 = require("../../Render"); -var Geo_1 = require("../../Geo"); -var MarkerSet = (function () { - function MarkerSet() { - this._create$ = new Subject_1.Subject(); - this._remove$ = new Subject_1.Subject(); - this._update$ = new Subject_1.Subject(); - // markers list stream is the result of applying marker updates. - this._markers$ = this._update$ - .scan(function (markers, operation) { - return operation(markers); - }, { hash: {}, spatial: rbush(16, [".lon", ".lat", ".lon", ".lat"]) }) - .map(function (markers) { - return markers.spatial; - }) - .publishReplay(1) - .refCount(); - // creation stream generate creation updates from given markers. - this._create$ - .map(function (marker) { - return function (markers) { - if (markers.hash[marker.id]) { - markers.spatial.remove(markers.hash[marker.id]); - } - var rbushObj = { - id: marker.id, - lat: marker.latLonAlt.lat, - lon: marker.latLonAlt.lon, - marker: marker, - }; - markers.spatial.insert(rbushObj); - markers.hash[marker.id] = rbushObj; - return markers; - }; - }) - .subscribe(this._update$); - // remove stream generates remove updates from given markers - this._remove$ - .map(function (id) { - return function (markers) { - var rbushObj = markers.hash[id]; - markers.spatial.remove(rbushObj); - delete markers.hash[id]; - return markers; - }; - }) - .subscribe(this._update$); - } - MarkerSet.prototype.addMarker = function (marker) { - this._create$.next(marker); - }; - MarkerSet.prototype.removeMarker = function (id) { - this._remove$.next(id); - }; - Object.defineProperty(MarkerSet.prototype, "markers$", { + Object.defineProperty(SequenceDOMRenderer.prototype, "index$", { get: function () { - return this._markers$; + return this._notifyIndexChanged$; }, enumerable: true, configurable: true }); - return MarkerSet; -}()); -exports.MarkerSet = MarkerSet; -var MarkerComponent = (function (_super) { - __extends(MarkerComponent, _super); - function MarkerComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - } - MarkerComponent.prototype._activate = function () { + Object.defineProperty(SequenceDOMRenderer.prototype, "mouseEnterDirection$", { + get: function () { + return this._mouseEnterDirection$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SequenceDOMRenderer.prototype, "mouseLeaveDirection$", { + get: function () { + return this._mouseLeaveDirection$; + }, + enumerable: true, + configurable: true + }); + SequenceDOMRenderer.prototype.activate = function () { var _this = this; - this._scene = new THREE.Scene(); - this._markerSet = new MarkerSet(); - this._markerObjects = {}; - this._disposable = Observable_1.Observable - .combineLatest([ - this._navigator.stateService.currentState$, - this._markerSet.markers$, - ], function (frame, markers) { - return { frame: frame, markers: markers }; - }) - .distinctUntilChanged(undefined, function (args) { - return args.frame.id; - }) - .map(function (args) { - return _this._renderHash(args); - }) - .subscribe(this._container.glRenderer.render$); + if (!!this._changingSubscription) { + return; + } + this._changingSubscription = Observable_1.Observable + .merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$ + .filter(function (touchEvent) { + return touchEvent.touches.length === 0; + })) + .subscribe(function (event) { + if (_this._changingSpeed) { + _this._changingSpeed = false; + } + if (_this._changingPosition) { + _this._setChangingPosition(false); + } + }); }; - MarkerComponent.prototype._deactivate = function () { - // release memory - this._disposeScene(); - this._disposable.unsubscribe(); + SequenceDOMRenderer.prototype.deactivate = function () { + if (!this._changingSubscription) { + return; + } + this._changingSpeed = false; + this._changingPosition = false; + this._expandControls = false; + this._mode = Component_1.SequenceMode.Default; + this._changingSubscription.unsubscribe(); + this._changingSubscription = null; }; - MarkerComponent.prototype._getDefaultConfiguration = function () { - return {}; + SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, speed, index, max, component, navigator) { + if (configuration.visible === false) { + return vd.h("div.SequenceContainer", {}, []); + } + var stepper = this._createStepper(edgeStatus, configuration, containerWidth, component, navigator); + var controls = this._createSequenceControls(containerWidth); + var playback = this._createPlaybackControls(containerWidth, speed, component, configuration); + var timeline = this._createTimelineControls(containerWidth, index, max); + return vd.h("div.SequenceContainer", [stepper, controls, playback, timeline]); }; - MarkerComponent.prototype.createMarker = function (latLonAlt, markerOptions) { - if (markerOptions.type === "marker") { - return new Component_1.SimpleMarker(latLonAlt, markerOptions); + SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) { + var elementWidth = element.offsetWidth; + var elementHeight = element.offsetHeight; + var minWidth = configuration.minWidth; + var maxWidth = configuration.maxWidth; + if (maxWidth < minWidth) { + maxWidth = minWidth; } - return null; + var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth); + var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight); + var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight))); + return minWidth + coeff * (maxWidth - minWidth); }; - MarkerComponent.prototype.addMarker = function (marker) { - this._markerSet.addMarker(marker); + SequenceDOMRenderer.prototype._createPositionInput = function (index, max) { + var _this = this; + this._index = index; + var onPosition = function (e) { + _this._index = Number(e.target.value); + _this._notifyIndexChanged$.next(_this._index); + }; + var boundingRect = this._container.domContainer.getBoundingClientRect(); + var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 65; + var onStart = function (e) { + e.stopPropagation(); + _this._setChangingPosition(true); + }; + var onMove = function (e) { + if (_this._changingPosition === true) { + e.stopPropagation(); + } + }; + var onKeyDown = function (e) { + if (e.key === "ArrowDown" || e.key === "ArrowLeft" || + e.key === "ArrowRight" || e.key === "ArrowUp") { + e.preventDefault(); + } + }; + var positionInputProperties = { + max: max != null ? max : 1, + min: 0, + onchange: onPosition, + oninput: onPosition, + onkeydown: onKeyDown, + onmousedown: onStart, + onmousemove: onMove, + ontouchmove: onMove, + ontouchstart: onStart, + style: { + width: width + "px", + }, + type: "range", + value: index != null ? index : 0, + }; + var disabled = index == null || max == null || max <= 1; + if (disabled) { + positionInputProperties.disabled = "true"; + } + var positionInput = vd.h("input.SequencePosition", positionInputProperties, []); + var positionContainerClass = disabled ? ".SequencePositionContainerDisabled" : ".SequencePositionContainer"; + return vd.h("div" + positionContainerClass, [positionInput]); }; - Object.defineProperty(MarkerComponent.prototype, "markers$", { - get: function () { - return this._markerSet.markers$; - }, - enumerable: true, - configurable: true - }); - MarkerComponent.prototype.removeMarker = function (id) { - this._markerSet.removeMarker(id); + SequenceDOMRenderer.prototype._createSpeedInput = function (speed) { + var _this = this; + this._speed = speed; + var onSpeed = function (e) { + _this._speed = Number(e.target.value) / 1000; + _this._notifySpeedChanged$.next(_this._speed); + }; + var boundingRect = this._container.domContainer.getBoundingClientRect(); + var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 160; + var onStart = function (e) { + _this._changingSpeed = true; + e.stopPropagation(); + }; + var onMove = function (e) { + if (_this._changingSpeed === true) { + e.stopPropagation(); + } + }; + var onKeyDown = function (e) { + if (e.key === "ArrowDown" || e.key === "ArrowLeft" || + e.key === "ArrowRight" || e.key === "ArrowUp") { + e.preventDefault(); + } + }; + var speedInput = vd.h("input.SequenceSpeed", { + max: 1000, + min: 0, + onchange: onSpeed, + oninput: onSpeed, + onkeydown: onKeyDown, + onmousedown: onStart, + onmousemove: onMove, + ontouchmove: onMove, + ontouchstart: onStart, + style: { + width: width + "px", + }, + type: "range", + value: 1000 * speed, + }, []); + return vd.h("div.SequenceSpeedContainer", [speedInput]); }; - MarkerComponent.prototype._renderHash = function (args) { - // determine if render is needed while updating scene - // specific properies. - var needsRender = this._updateScene(args); - // return render hash with render function and - // render in foreground. - return { - name: this._name, - render: { - frameId: args.frame.id, - needsRender: needsRender, - render: this._render.bind(this), - stage: Render_1.GLRenderStage.Foreground, + SequenceDOMRenderer.prototype._createPlaybackControls = function (containerWidth, speed, component, configuration) { + var _this = this; + if (this._mode !== Component_1.SequenceMode.Playback) { + return vd.h("div.SequencePlayback", []); + } + var switchIcon = vd.h("div.SequenceSwitchIcon.SequenceIconVisible", []); + var direction = configuration.direction === Edge_1.EdgeDirection.Next ? + Edge_1.EdgeDirection.Prev : Edge_1.EdgeDirection.Next; + var playing = configuration.playing; + var switchButtonProperties = { + onclick: function () { + if (!playing) { + component.setDirection(direction); + } + }, + }; + var switchButtonClassName = configuration.playing ? ".SequenceSwitchButtonDisabled" : ".SequenceSwitchButton"; + var switchButton = vd.h("div" + switchButtonClassName, switchButtonProperties, [switchIcon]); + var slowIcon = vd.h("div.SequenceSlowIcon.SequenceIconVisible", []); + var slowContainer = vd.h("div.SequenceSlowContainer", [slowIcon]); + var fastIcon = vd.h("div.SequenceFastIcon.SequenceIconVisible", []); + var fastContainer = vd.h("div.SequenceFastContainer", [fastIcon]); + var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []); + var closeButtonProperties = { + onclick: function () { + _this._mode = Component_1.SequenceMode.Default; + _this._notifyChanged$.next(_this); }, }; + var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]); + var speedInput = this._createSpeedInput(speed); + var playbackChildren = [switchButton, slowContainer, speedInput, fastContainer, closeButton]; + var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10); + var playbackProperties = { style: { top: top + "px" } }; + return vd.h("div.SequencePlayback", playbackProperties, playbackChildren); }; - MarkerComponent.prototype._updateScene = function (args) { - if (!args.frame || - !args.markers || - !args.frame.state.currentNode) { - return false; + SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) { + var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null || + configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null; + var onclick = configuration.playing ? + function (e) { component.stop(); } : + canPlay ? function (e) { component.play(); } : null; + var buttonProperties = { onclick: onclick }; + var iconClass = configuration.playing ? + "Stop" : + canPlay ? "Play" : "PlayDisabled"; + var iconProperties = { className: iconClass }; + if (configuration.direction === Edge_1.EdgeDirection.Prev) { + iconProperties.style = { + transform: "rotate(180deg) translate(50%, 50%)", + }; } - var needRender = false; - var oldObjects = this._markerObjects; - var node = args.frame.state.currentNode; - this._markerObjects = {}; - var boxWidth = 0.001; - var minLon = node.latLon.lon - boxWidth / 2; - var minLat = node.latLon.lat - boxWidth / 2; - var maxLon = node.latLon.lon + boxWidth / 2; - var maxLat = node.latLon.lat + boxWidth / 2; - var markers = _.map(args.markers.search({ maxX: maxLon, maxY: maxLat, minX: minLon, minY: minLat }), function (item) { - return item.marker; - }).filter(function (marker) { - return marker.visibleInKeys.length === 0 || _.contains(marker.visibleInKeys, node.key); - }); - for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) { - var marker = markers_1[_i]; - if (marker.id in oldObjects) { - this._markerObjects[marker.id] = oldObjects[marker.id]; - delete oldObjects[marker.id]; - } - else { - var reference = args.frame.state.reference; - var p = (new Geo_1.GeoCoords).geodeticToEnu(marker.latLonAlt.lat, marker.latLonAlt.lon, marker.latLonAlt.alt, reference.lat, reference.lon, reference.alt); - var o = marker.createGeometry(); - o.position.set(p[0], p[1], p[2]); - this._scene.add(o); - this._markerObjects[marker.id] = o; - needRender = true; + var icon = vd.h("div.SequenceComponentIcon", iconProperties, []); + var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled"; + return vd.h("div." + buttonClass, buttonProperties, [icon]); + }; + SequenceDOMRenderer.prototype._createSequenceControls = function (containerWidth) { + var _this = this; + var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth); + var expanderProperties = { + onclick: function () { + _this._expandControls = !_this._expandControls; + _this._mode = Component_1.SequenceMode.Default; + _this._notifyChanged$.next(_this); + }, + style: { + "border-bottom-right-radius": borderRadius + "px", + "border-top-right-radius": borderRadius + "px", + }, + }; + var expanderBar = vd.h("div.SequenceExpanderBar", []); + var expander = vd.h("div.SequenceExpanderButton", expanderProperties, [expanderBar]); + var fastIconClassName = this._mode === Component_1.SequenceMode.Playback ? + ".SequenceFastIconGrey.SequenceIconVisible" : ".SequenceFastIcon"; + var fastIcon = vd.h("div" + fastIconClassName, []); + var playbackProperties = { + onclick: function () { + _this._mode = _this._mode === Component_1.SequenceMode.Playback ? + Component_1.SequenceMode.Default : + Component_1.SequenceMode.Playback; + _this._notifyChanged$.next(_this); + }, + }; + var playback = vd.h("div.SequencePlaybackButton", playbackProperties, [fastIcon]); + var timelineIconClassName = this._mode === Component_1.SequenceMode.Timeline ? + ".SequenceTimelineIconGrey.SequenceIconVisible" : ".SequenceTimelineIcon"; + var timelineIcon = vd.h("div" + timelineIconClassName, []); + var timelineProperties = { + onclick: function () { + _this._mode = _this._mode === Component_1.SequenceMode.Timeline ? + Component_1.SequenceMode.Default : + Component_1.SequenceMode.Timeline; + _this._notifyChanged$.next(_this); + }, + }; + var timeline = vd.h("div.SequenceTimelineButton", timelineProperties, [timelineIcon]); + var properties = { + style: { + height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px", + transform: "translate(" + (containerWidth / 2 + 2) + "px, 0)", + width: (this._controlsDefaultWidth / this._stepperDefaultWidth * containerWidth) + "px", + }, + }; + var className = ".SequenceControls" + + (this._expandControls ? ".SequenceControlsExpanded" : ""); + return vd.h("div" + className, properties, [playback, timeline, expander]); + }; + SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, containerWidth, configuration, navigator) { + var _this = this; + var nextProperties = { + onclick: nextKey != null ? + function (e) { + navigator.moveDir$(Edge_1.EdgeDirection.Next) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); + } + }); + } : + null, + onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); }, + onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); }, + }; + var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth); + var prevProperties = { + onclick: prevKey != null ? + function (e) { + navigator.moveDir$(Edge_1.EdgeDirection.Prev) + .subscribe(undefined, function (error) { + if (!(error instanceof Error_1.AbortMapillaryError)) { + console.error(error); + } + }); + } : + null, + onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); }, + onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); }, + style: { + "border-bottom-left-radius": borderRadius + "px", + "border-top-left-radius": borderRadius + "px", + }, + }; + var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey); + var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey); + var nextIcon = vd.h("div.SequenceComponentIcon", []); + var prevIcon = vd.h("div.SequenceComponentIcon", []); + return [ + vd.h("div." + prevClass, prevProperties, [prevIcon]), + vd.h("div." + nextClass, nextProperties, [nextIcon]), + ]; + }; + SequenceDOMRenderer.prototype._createStepper = function (edgeStatus, configuration, containerWidth, component, navigator) { + var nextKey = null; + var prevKey = null; + for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { + var edge = _a[_i]; + if (edge.data.direction === Edge_1.EdgeDirection.Next) { + nextKey = edge.to; } - } - for (var i in oldObjects) { - if (oldObjects.hasOwnProperty(i)) { - this._disposeObject(oldObjects[i]); - needRender = true; + if (edge.data.direction === Edge_1.EdgeDirection.Prev) { + prevKey = edge.to; } } - return needRender; + var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component); + var buttons = this._createSequenceArrows(nextKey, prevKey, containerWidth, configuration, navigator); + buttons.splice(1, 0, playingButton); + var containerProperties = { + oncontextmenu: function (event) { event.preventDefault(); }, + style: { + height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px", + width: containerWidth + "px", + }, + }; + return vd.h("div.SequenceStepper", containerProperties, buttons); }; - MarkerComponent.prototype._render = function (perspectiveCamera, renderer) { - renderer.render(this._scene, perspectiveCamera); + SequenceDOMRenderer.prototype._createTimelineControls = function (containerWidth, index, max) { + var _this = this; + if (this._mode !== Component_1.SequenceMode.Timeline) { + return vd.h("div.SequenceTimeline", []); + } + var positionInput = this._createPositionInput(index, max); + var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []); + var closeButtonProperties = { + onclick: function () { + _this._mode = Component_1.SequenceMode.Default; + _this._notifyChanged$.next(_this); + }, + }; + var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]); + var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10); + var playbackProperties = { style: { top: top + "px" } }; + return vd.h("div.SequenceTimeline", playbackProperties, [positionInput, closeButton]); }; - MarkerComponent.prototype._disposeObject = function (object) { - this._scene.remove(object); - for (var i = 0; i < object.children.length; ++i) { - var c = object.children[i]; - c.geometry.dispose(); - c.material.dispose(); + SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) { + var className = direction === Edge_1.EdgeDirection.Next ? + "SequenceStepNext" : + "SequenceStepPrev"; + if (key == null) { + className += "Disabled"; } - }; - MarkerComponent.prototype._disposeScene = function () { - for (var i in this._markerObjects) { - if (this._markerObjects.hasOwnProperty(i)) { - this._disposeObject(this._markerObjects[i]); + else { + if (highlightKey === key) { + className += "Highlight"; } } - this._markerObjects = {}; + return className; }; - MarkerComponent.componentName = "marker"; - return MarkerComponent; -}(Component_1.Component)); -exports.MarkerComponent = MarkerComponent; -Component_1.ComponentService.register(MarkerComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = MarkerComponent; + SequenceDOMRenderer.prototype._setChangingPosition = function (value) { + this._changingPosition = value; + this._notifyChangingPositionChanged$.next(value); + }; + return SequenceDOMRenderer; +}()); +exports.SequenceDOMRenderer = SequenceDOMRenderer; +exports.default = SequenceDOMRenderer; -},{"../../Component":207,"../../Geo":210,"../../Render":213,"rbush":24,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/switchMap":73,"three":157,"underscore":158}],244:[function(require,module,exports){ +},{"../../Component":290,"../../Edge":291,"../../Error":292,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],348:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var THREE = require("three"); -var Component_1 = require("../../Component"); -var SimpleMarker = (function (_super) { - __extends(SimpleMarker, _super); - function SimpleMarker(latLonAlt, markerOptions) { - _super.call(this, latLonAlt, markerOptions); - this._circleToRayAngle = 2.0; - this._simpleMarkerStyle = markerOptions.style; - } - SimpleMarker.prototype.createGeometry = function () { - var radius = 2; - var cone = new THREE.Mesh(this._markerGeometry(radius, 16, 8), new THREE.MeshBasicMaterial({ - color: this._stringToRBG(this._simpleMarkerStyle.color), - depthWrite: false, - opacity: this._simpleMarkerStyle.opacity, - shading: THREE.SmoothShading, - transparent: true, - })); - var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 16, 8), new THREE.MeshBasicMaterial({ - color: this._stringToRBG(this._simpleMarkerStyle.ballColor), - depthWrite: false, - opacity: this._simpleMarkerStyle.ballOpacity, - shading: THREE.SmoothShading, - transparent: true, - })); - ball.position.z = this._markerHeight(radius); - var group = new THREE.Object3D(); - group.add(ball); - group.add(cone); - return group; +Object.defineProperty(exports, "__esModule", { value: true }); +var SequenceMode; +(function (SequenceMode) { + SequenceMode[SequenceMode["Default"] = 0] = "Default"; + SequenceMode[SequenceMode["Playback"] = 1] = "Playback"; + SequenceMode[SequenceMode["Timeline"] = 2] = "Timeline"; +})(SequenceMode = exports.SequenceMode || (exports.SequenceMode = {})); +exports.default = SequenceMode; + +},{}],349:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); + +var path = require("path"); +var Shaders = /** @class */ (function () { + function Shaders() { + } + Shaders.equirectangular = { + fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vec3 b = normalize(vRstq.xyz);\n float lat = -asin(b.y);\n float lon = atan(b.x, b.z);\n float x = (lon - phiShift) / phiLength + 0.5;\n float y = (lat - thetaShift) / thetaLength + 0.5;\n vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n gl_FragColor = baseColor;\n}", + vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}", }; - SimpleMarker.prototype._markerHeight = function (radius) { - var t = Math.tan(Math.PI - this._circleToRayAngle); - return radius * Math.sqrt(1 + t * t); + Shaders.equirectangularCurtain = { + fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float curtain;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vec3 b = normalize(vRstq.xyz);\n float lat = -asin(b.y);\n float lon = atan(b.x, b.z);\n float x = (lon - phiShift) / phiLength + 0.5;\n float y = (lat - thetaShift) / thetaLength + 0.5;\n\n bool inverted = curtain < 0.5;\n\n float curtainMin = inverted ? curtain + 0.5 : curtain - 0.5;\n float curtainMax = curtain;\n\n bool insideCurtain = inverted ?\n x > curtainMin || x < curtainMax :\n x > curtainMin && x < curtainMax;\n\n vec4 baseColor;\n if (insideCurtain) {\n baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n } else {\n baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n\n gl_FragColor = baseColor;\n}", + vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}", }; - SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) { - var geometry = new THREE.Geometry(); - widthSegments = Math.max(3, Math.floor(widthSegments) || 8); - heightSegments = Math.max(2, Math.floor(heightSegments) || 6); - var height = this._markerHeight(radius); - var vertices = []; - for (var y = 0; y <= heightSegments; ++y) { - var verticesRow = []; - for (var x = 0; x <= widthSegments; ++x) { - var u = x / widthSegments * Math.PI * 2; - var v = y / heightSegments * Math.PI; - var r = void 0; - if (v < this._circleToRayAngle) { - r = radius; - } - else { - var t = Math.tan(v - this._circleToRayAngle); - r = radius * Math.sqrt(1 + t * t); - } - var vertex = new THREE.Vector3(); - vertex.x = r * Math.cos(u) * Math.sin(v); - vertex.y = r * Math.sin(u) * Math.sin(v); - vertex.z = r * Math.cos(v) + height; - geometry.vertices.push(vertex); - verticesRow.push(geometry.vertices.length - 1); - } - vertices.push(verticesRow); - } - for (var y = 0; y < heightSegments; ++y) { - for (var x = 0; x < widthSegments; ++x) { - var v1 = vertices[y][x + 1]; - var v2 = vertices[y][x]; - var v3 = vertices[y + 1][x]; - var v4 = vertices[y + 1][x + 1]; - var n1 = geometry.vertices[v1].clone().normalize(); - var n2 = geometry.vertices[v2].clone().normalize(); - var n3 = geometry.vertices[v3].clone().normalize(); - var n4 = geometry.vertices[v4].clone().normalize(); - geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4])); - geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()])); - } - } - geometry.computeFaceNormals(); - geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height); - return geometry; + Shaders.perspective = { + fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform vec4 bbox;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n float x = vRstq.x / vRstq.w;\n float y = vRstq.y / vRstq.w;\n\n vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n\n gl_FragColor = baseColor;\n}", + vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}", }; - SimpleMarker.prototype._stringToRBG = function (str) { - var ret = 0; - for (var i = 0; i < str.length; i++) { - ret = str.charCodeAt(i) + ((ret << 5) - ret); - } - return ret; + Shaders.perspectiveCurtain = { + fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float curtain;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n float x = vRstq.x / vRstq.w;\n float y = vRstq.y / vRstq.w;\n\n vec4 baseColor;\n if (x < curtain || curtain >= 1.0) {\n baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n } else {\n baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n\n gl_FragColor = baseColor;\n}\n", + vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}", }; - return SimpleMarker; -}(Component_1.Marker)); -exports.SimpleMarker = SimpleMarker; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SimpleMarker; + return Shaders; +}()); +exports.Shaders = Shaders; -},{"../../Component":207,"three":157}],245:[function(require,module,exports){ -/// +},{"path":22}],350:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/observable/of"); -require("rxjs/add/operator/concat"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/finally"); -require("rxjs/add/operator/first"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/share"); -require("rxjs/add/operator/switchMap"); -require("rxjs/add/operator/takeUntil"); -require("rxjs/add/operator/withLatestFrom"); var Component_1 = require("../../Component"); -var Edge_1 = require("../../Edge"); +var Geo_1 = require("../../Geo"); +var State_1 = require("../../State"); +var Render_1 = require("../../Render"); +var Tiles_1 = require("../../Tiles"); +var Utils_1 = require("../../Utils"); /** - * @class SequenceComponent - * @classdesc Component showing navigation arrows for sequence directions - * as well as playing button. Exposes an API to start and stop play. + * @class SliderComponent + * + * @classdesc Component for comparing pairs of images. Renders + * a slider for adjusting the curtain of the first image. + * + * Deactivate the sequence, direction and image plane + * components when activating the slider component to avoid + * interfering UI elements. + * + * To retrive and use the marker component + * + * @example + * ``` + * var viewer = new Mapillary.Viewer( + * "", + * "", + * ""); + * + * viewer.deactivateComponent("imagePlane"); + * viewer.deactivateComponent("direction"); + * viewer.deactivateComponent("sequence"); + * + * viewer.activateComponent("slider"); + * + * var sliderComponent = viewer.getComponent("marker"); + * ``` */ -var SequenceComponent = (function (_super) { - __extends(SequenceComponent, _super); - function SequenceComponent(name, container, navigator) { - _super.call(this, name, container, navigator); - this._nodesAhead = 5; - this._configurationOperation$ = new Subject_1.Subject(); - this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element); - this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction(); - this._containerWidth$ = new Subject_1.Subject(); - this._hoveredKeySubject$ = new Subject_1.Subject(); - this._hoveredKey$ = this._hoveredKeySubject$.share(); - this._edgeStatus$ = this._navigator.stateService.currentNode$ - .switchMap(function (node) { - return node.sequenceEdges$; +var SliderComponent = /** @class */ (function (_super) { + __extends(SliderComponent, _super); + function SliderComponent(name, container, navigator, viewportCoords) { + var _this = _super.call(this, name, container, navigator) || this; + _this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords(); + _this._domRenderer = new Component_1.SliderDOMRenderer(container); + _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin); + _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator(); + _this._spatial = new Geo_1.Spatial(); + _this._glRendererOperation$ = new Subject_1.Subject(); + _this._glRendererCreator$ = new Subject_1.Subject(); + _this._glRendererDisposer$ = new Subject_1.Subject(); + _this._glRenderer$ = _this._glRendererOperation$ + .scan(function (glRenderer, operation) { + return operation(glRenderer); + }, null) + .filter(function (glRenderer) { + return glRenderer != null; }) - .publishReplay(1) - .refCount(); + .distinctUntilChanged(undefined, function (glRenderer) { + return glRenderer.frameId; + }); + _this._glRendererCreator$ + .map(function () { + return function (glRenderer) { + if (glRenderer != null) { + throw new Error("Multiple slider states can not be created at the same time"); + } + return new Component_1.SliderGLRenderer(); + }; + }) + .subscribe(_this._glRendererOperation$); + _this._glRendererDisposer$ + .map(function () { + return function (glRenderer) { + glRenderer.dispose(); + return null; + }; + }) + .subscribe(_this._glRendererOperation$); + return _this; } - Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", { - /** - * Get hovered key observable. - * - * @description An observable emitting the key of the node for the direction - * arrow that is being hovered. When the mouse leaves a direction arrow null - * is emitted. - * - * @returns {Observable} - */ - get: function () { - return this._hoveredKey$; - }, - enumerable: true, - configurable: true - }); - /** - * Start playing. - * - * @fires PlayerComponent#playingchanged - */ - SequenceComponent.prototype.play = function () { - this.configure({ playing: true }); - }; - /** - * Stop playing. - * - * @fires PlayerComponent#playingchanged - */ - SequenceComponent.prototype.stop = function () { - this.configure({ playing: false }); - }; - /** - * Set the direction to follow when playing. - * - * @param {EdgeDirection} direction - The direction that will be followed when playing. - */ - SequenceComponent.prototype.setDirection = function (direction) { - this.configure({ direction: direction }); - }; /** - * Set highlight key. + * Set the initial position. * - * @description The arrow pointing towards the node corresponding to the - * highlight key will be highlighted. + * @description Configures the intial position of the slider. + * The inital position value will be used when the component + * is activated. * - * @param {string} highlightKey Key of node to be highlighted if existing. + * @param {number} initialPosition - Initial slider position. */ - SequenceComponent.prototype.setHighlightKey = function (highlightKey) { - this.configure({ highlightKey: highlightKey }); + SliderComponent.prototype.setInitialPosition = function (initialPosition) { + this.configure({ initialPosition: initialPosition }); }; /** - * Set max width of container element. - * - * @description Set max width of the container element holding - * the sequence navigation elements. If the min width is larger than the - * max width the min width value will be used. + * Set the image keys. * - * The container element is automatically resized when the resize - * method on the Viewer class is called. + * @description Configures the component to show the image + * planes for the supplied image keys. * - * @param {number} minWidth + * @param {ISliderKeys} keys - Slider keys object specifying + * the images to be shown in the foreground and the background. */ - SequenceComponent.prototype.setMaxWidth = function (maxWidth) { - this.configure({ maxWidth: maxWidth }); + SliderComponent.prototype.setKeys = function (keys) { + this.configure({ keys: keys }); }; /** - * Set min width of container element. - * - * @description Set min width of the container element holding - * the sequence navigation elements. If the min width is larger than the - * max width the min width value will be used. + * Set the slider mode. * - * The container element is automatically resized when the resize - * method on the Viewer class is called. + * @description Configures the mode for transitions between + * image pairs. * - * @param {number} minWidth + * @param {SliderMode} mode - Slider mode to be set. */ - SequenceComponent.prototype.setMinWidth = function (minWidth) { - this.configure({ minWidth: minWidth }); + SliderComponent.prototype.setSliderMode = function (mode) { + this.configure({ mode: mode }); }; /** - * Set the value indicating whether the sequence UI elements should be visible. + * Set the value controlling if the slider is visible. * - * @param {boolean} visible + * @param {boolean} sliderVisible - Value indicating if + * the slider should be visible or not. */ - SequenceComponent.prototype.setVisible = function (visible) { - this.configure({ visible: visible }); + SliderComponent.prototype.setSliderVisible = function (sliderVisible) { + this.configure({ sliderVisible: sliderVisible }); }; - /** @inheritdoc */ - SequenceComponent.prototype.resize = function () { + SliderComponent.prototype._activate = function () { var _this = this; - this._configuration$ + this._modeSubcription = this._domRenderer.mode$ + .subscribe(function (mode) { + _this.setSliderMode(mode); + }); + this._glRenderSubscription = this._glRenderer$ + .map(function (glRenderer) { + var renderHash = { + name: _this._name, + render: { + frameId: glRenderer.frameId, + needsRender: glRenderer.needsRender, + render: glRenderer.render.bind(glRenderer), + stage: Render_1.GLRenderStage.Background, + }, + }; + return renderHash; + }) + .subscribe(this._container.glRenderer.render$); + var position$ = this.configuration$ + .map(function (configuration) { + return configuration.initialPosition != null ? + configuration.initialPosition : 1; + }) .first() + .concat(this._domRenderer.position$); + var mode$ = this.configuration$ .map(function (configuration) { - return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration); + return configuration.mode; }) - .subscribe(function (containerWidth) { - _this._containerWidth$.next(containerWidth); - }); - }; - SequenceComponent.prototype._activate = function () { - var _this = this; - this._renderSubscription = Observable_1.Observable - .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$) - .map(function (ec) { - var edgeStatus = ec[0]; - var configuration = ec[1]; - var containerWidth = ec[2]; - var vNode = _this._sequenceDOMRenderer - .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator); - return { name: _this._name, vnode: vNode }; + .distinctUntilChanged(); + var motionless$ = this._navigator.stateService.currentState$ + .map(function (frame) { + return frame.state.motionless; }) - .subscribe(this._container.domRenderer.render$); - this._containerWidthSubscription = this._configuration$ - .distinctUntilChanged(function (value1, value2) { - return value1[0] === value2[0] && value1[1] === value2[1]; - }, function (configuration) { - return [configuration.minWidth, configuration.maxWidth]; + .distinctUntilChanged(); + var fullPano$ = this._navigator.stateService.currentState$ + .map(function (frame) { + return frame.state.currentNode.fullPano; }) + .distinctUntilChanged(); + var sliderVisible$ = Observable_1.Observable + .combineLatest(this._configuration$ .map(function (configuration) { - return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration); + return configuration.sliderVisible; + }), this._navigator.stateService.currentState$ + .map(function (frame) { + return !(frame.state.currentNode == null || + frame.state.previousNode == null || + (frame.state.currentNode.pano && !frame.state.currentNode.fullPano) || + (frame.state.previousNode.pano && !frame.state.previousNode.fullPano) || + (frame.state.currentNode.fullPano && !frame.state.previousNode.fullPano)); }) - .subscribe(this._containerWidth$); - this._configurationSubscription = this._configurationOperation$ - .scan(function (configuration, operation) { - return operation(configuration); - }, { playing: false }) - .finally(function () { - if (_this._playingSubscription != null) { - _this._navigator.stateService.cutNodes(); - _this._stop(); + .distinctUntilChanged()) + .map(function (_a) { + var sliderVisible = _a[0], enabledState = _a[1]; + return sliderVisible && enabledState; + }) + .distinctUntilChanged(); + this._waitSubscription = Observable_1.Observable + .combineLatest(mode$, motionless$, fullPano$, sliderVisible$) + .withLatestFrom(this._navigator.stateService.state$) + .subscribe(function (_a) { + var _b = _a[0], mode = _b[0], motionless = _b[1], fullPano = _b[2], sliderVisible = _b[3], state = _a[1]; + var interactive = sliderVisible && + (motionless || mode === Component_1.SliderMode.Stationary || fullPano); + if (interactive && state !== State_1.State.WaitingInteractively) { + _this._navigator.stateService.waitInteractively(); + } + else if (!interactive && state !== State_1.State.Waiting) { + _this._navigator.stateService.wait(); + } + }); + this._moveSubscription = Observable_1.Observable + .combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$) + .subscribe(function (_a) { + var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4]; + if (motionless || mode === Component_1.SliderMode.Stationary || fullPano) { + _this._navigator.stateService.moveTo(1); } + else { + _this._navigator.stateService.moveTo(position); + } + }); + this._domRenderSubscription = Observable_1.Observable + .combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$, this._container.renderService.size$) + .map(function (_a) { + var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4], size = _a[5]; + return { + name: _this._name, + vnode: _this._domRenderer.render(position, mode, motionless, fullPano, sliderVisible), + }; }) - .subscribe(); - this._configuration$ - .map(function (newConfiguration) { - return function (configuration) { - if (newConfiguration.playing !== configuration.playing) { - _this._navigator.stateService.cutNodes(); - if (newConfiguration.playing) { - _this._play(); - } - else { - _this._stop(); - } - } - configuration.playing = newConfiguration.playing; - return configuration; + .subscribe(this._container.domRenderer.render$); + this._glRendererCreator$.next(null); + this._updateCurtainSubscription = Observable_1.Observable + .combineLatest(position$, fullPano$, sliderVisible$, this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .map(function (_a) { + var position = _a[0], fullPano = _a[1], visible = _a[2], render = _a[3], transform = _a[4]; + if (!fullPano) { + return visible ? position : 1; + } + var basicMin = _this._viewportCoords.viewportToBasic(-1.15, 0, transform, render.perspective); + var basicMax = _this._viewportCoords.viewportToBasic(1.15, 0, transform, render.perspective); + var shiftedMax = basicMax[0] < basicMin[0] ? basicMax[0] + 1 : basicMax[0]; + var basicPosition = basicMin[0] + position * (shiftedMax - basicMin[0]); + return basicPosition > 1 ? basicPosition - 1 : basicPosition; + }) + .map(function (position) { + return function (glRenderer) { + glRenderer.updateCurtain(position); + return glRenderer; + }; + }) + .subscribe(this._glRendererOperation$); + this._stateSubscription = Observable_1.Observable + .combineLatest(this._navigator.stateService.currentState$, mode$) + .map(function (_a) { + var frame = _a[0], mode = _a[1]; + return function (glRenderer) { + glRenderer.update(frame, mode); + return glRenderer; }; }) - .subscribe(this._configurationOperation$); - this._stopSubscription = this._configuration$ + .subscribe(this._glRendererOperation$); + this._setKeysSubscription = this._configuration$ + .filter(function (configuration) { + return configuration.keys != null; + }) .switchMap(function (configuration) { - var edgeStatus$ = configuration.playing ? - _this._edgeStatus$ : - Observable_1.Observable.empty(); - var edgeDirection$ = Observable_1.Observable - .of(configuration.direction); return Observable_1.Observable - .combineLatest(edgeStatus$, edgeDirection$); + .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground)) + .map(function (nodes) { + return { background: nodes[0], foreground: nodes[1] }; + }) + .zip(_this._navigator.stateService.currentState$.first()) + .map(function (nf) { + return { nodes: nf[0], state: nf[1].state }; + }); }) - .map(function (ne) { - var edgeStatus = ne[0]; - var direction = ne[1]; - if (!edgeStatus.cached) { - return true; + .subscribe(function (co) { + if (co.state.currentNode != null && + co.state.previousNode != null && + co.state.currentNode.key === co.nodes.foreground.key && + co.state.previousNode.key === co.nodes.background.key) { + return; } - for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { - var edge = _a[_i]; - if (edge.data.direction === direction) { - return true; - } + if (co.state.currentNode.key === co.nodes.background.key) { + _this._navigator.stateService.setNodes([co.nodes.foreground]); + return; } - return false; + if (co.state.currentNode.key === co.nodes.foreground.key && + co.state.trajectory.length === 1) { + _this._navigator.stateService.prependNodes([co.nodes.background]); + return; + } + _this._navigator.stateService.setNodes([co.nodes.background]); + _this._navigator.stateService.setNodes([co.nodes.foreground]); + }, function (e) { + console.error(e); + }); + var previousNode$ = this._navigator.stateService.currentState$ + .map(function (frame) { + return frame.state.previousNode; }) - .filter(function (hasEdge) { - return !hasEdge; + .filter(function (node) { + return node != null; }) - .map(function (hasEdge) { - return { playing: false }; + .distinctUntilChanged(undefined, function (node) { + return node.key; + }); + var textureProvider$ = this._navigator.stateService.currentState$ + .distinctUntilChanged(undefined, function (frame) { + return frame.state.currentNode.key; }) - .subscribe(this._configurationSubject$); - this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$ - .switchMap(function (direction) { - return _this._edgeStatus$ - .map(function (edgeStatus) { - for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { - var edge = _a[_i]; - if (edge.data.direction === direction) { - return edge.to; - } - } - return null; - }) - .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$) - .concat(Observable_1.Observable.of(null)); + .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$) + .map(function (_a) { + var frame = _a[0], renderer = _a[1], size = _a[2]; + var state = frame.state; + var viewportSize = Math.max(size.width, size.height); + var currentNode = state.currentNode; + var currentTransform = state.currentTransform; + var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512; + return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer); + }) + .publishReplay(1) + .refCount(); + this._textureProviderSubscription = textureProvider$.subscribe(function () { }); + this._setTextureProviderSubscription = textureProvider$ + .map(function (provider) { + return function (renderer) { + renderer.setTextureProvider(provider.key, provider); + return renderer; + }; + }) + .subscribe(this._glRendererOperation$); + this._setTileSizeSubscription = this._container.renderService.size$ + .switchMap(function (size) { + return Observable_1.Observable + .combineLatest(textureProvider$, Observable_1.Observable.of(size)) + .first(); + }) + .subscribe(function (_a) { + var provider = _a[0], size = _a[1]; + var viewportSize = Math.max(size.width, size.height); + var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512; + provider.setTileSize(tileSize); + }); + this._abortTextureProviderSubscription = textureProvider$ + .pairwise() + .subscribe(function (pair) { + var previous = pair[0]; + previous.abort(); + }); + var roiTrigger$ = Observable_1.Observable + .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250)) + .map(function (_a) { + var camera = _a[0], size = _a[1]; + return [ + camera.camera.position.clone(), + camera.camera.lookat.clone(), + camera.zoom.valueOf(), + size.height.valueOf(), + size.width.valueOf() + ]; + }) + .pairwise() + .skipWhile(function (pls) { + return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0; + }) + .map(function (pls) { + var samePosition = pls[0][0].equals(pls[1][0]); + var sameLookat = pls[0][1].equals(pls[1][1]); + var sameZoom = pls[0][2] === pls[1][2]; + var sameHeight = pls[0][3] === pls[1][3]; + var sameWidth = pls[0][4] === pls[1][4]; + return samePosition && sameLookat && sameZoom && sameHeight && sameWidth; }) .distinctUntilChanged() - .subscribe(this._hoveredKeySubject$); - }; - SequenceComponent.prototype._deactivate = function () { - this._stopSubscription.unsubscribe(); - this._renderSubscription.unsubscribe(); - this._configurationSubscription.unsubscribe(); - this._containerWidthSubscription.unsubscribe(); - this._hoveredKeySubscription.unsubscribe(); - this.stop(); - }; - SequenceComponent.prototype._getDefaultConfiguration = function () { - return { - direction: Edge_1.EdgeDirection.Next, - maxWidth: 117, - minWidth: 70, - playing: false, - visible: true, - }; - }; - SequenceComponent.prototype._play = function () { - var _this = this; - this._playingSubscription = this._navigator.stateService.currentState$ + .filter(function (stalled) { + return stalled; + }) + .switchMap(function (stalled) { + return _this._container.renderService.renderCameraFrame$ + .first(); + }) + .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$); + this._setRegionOfInterestSubscription = textureProvider$ + .switchMap(function (provider) { + return roiTrigger$ + .map(function (_a) { + var camera = _a[0], size = _a[1], transform = _a[2]; + return [ + _this._roiCalculator.computeRegionOfInterest(camera, size, transform), + provider, + ]; + }); + }) + .filter(function (args) { + return !args[1].disposed; + }) + .subscribe(function (args) { + var roi = args[0]; + var provider = args[1]; + provider.setRegionOfInterest(roi); + }); + var hasTexture$ = textureProvider$ + .switchMap(function (provider) { + return provider.hasTexture$; + }) + .startWith(false) + .publishReplay(1) + .refCount(); + this._hasTextureSubscription = hasTexture$.subscribe(function () { }); + var nodeImage$ = this._navigator.stateService.currentState$ .filter(function (frame) { - return frame.state.nodesAhead < _this._nodesAhead; + return frame.state.nodesAhead === 0; }) .map(function (frame) { - return frame.state.lastNode; + return frame.state.currentNode; }) - .distinctUntilChanged(undefined, function (lastNode) { - return lastNode.key; + .distinctUntilChanged(undefined, function (node) { + return node.key; }) - .withLatestFrom(this._configuration$, function (lastNode, configuration) { - return [lastNode, configuration.direction]; + .debounceTime(1000) + .withLatestFrom(hasTexture$) + .filter(function (args) { + return !args[1]; }) - .switchMap(function (nd) { - return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ? - nd[0].sequenceEdges$ : - nd[0].spatialEdges$) - .filter(function (status) { - return status.cached; - }) - .zip(Observable_1.Observable.of(nd[1]), function (status, direction) { - return [status, direction]; + .map(function (args) { + return args[0]; + }) + .filter(function (node) { + return node.pano ? + Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize : + Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize; + }) + .switchMap(function (node) { + var baseImageSize = node.pano ? + Utils_1.Settings.basePanoramaSize : + Utils_1.Settings.baseImageSize; + if (Math.max(node.image.width, node.image.height) > baseImageSize) { + return Observable_1.Observable.empty(); + } + var image$ = node + .cacheImage$(Utils_1.Settings.maxImageSize) + .map(function (n) { + return [n.image, n]; + }); + return image$ + .takeUntil(hasTexture$ + .filter(function (hasTexture) { + return hasTexture; + })) + .catch(function (error, caught) { + console.error("Failed to fetch high res image (" + node.key + ")", error); + return Observable_1.Observable.empty(); + }); + }) + .publish() + .refCount(); + this._updateBackgroundSubscription = nodeImage$ + .withLatestFrom(textureProvider$) + .subscribe(function (args) { + if (args[0][1].key !== args[1].key || + args[1].disposed) { + return; + } + args[1].updateBackground(args[0][0]); + }); + this._updateTextureImageSubscription = nodeImage$ + .map(function (imn) { + return function (renderer) { + renderer.updateTextureImage(imn[0], imn[1]); + return renderer; + }; + }) + .subscribe(this._glRendererOperation$); + var textureProviderPrev$ = this._navigator.stateService.currentState$ + .filter(function (frame) { + return !!frame.state.previousNode; + }) + .distinctUntilChanged(undefined, function (frame) { + return frame.state.previousNode.key; + }) + .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$) + .map(function (_a) { + var frame = _a[0], renderer = _a[1], size = _a[2]; + var state = frame.state; + var viewportSize = Math.max(size.width, size.height); + var previousNode = state.previousNode; + var previousTransform = state.previousTransform; + var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512; + return new Tiles_1.TextureProvider(previousNode.key, previousTransform.basicWidth, previousTransform.basicHeight, tileSize, previousNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer); + }) + .publishReplay(1) + .refCount(); + this._textureProviderSubscriptionPrev = textureProviderPrev$.subscribe(function () { }); + this._setTextureProviderSubscriptionPrev = textureProviderPrev$ + .map(function (provider) { + return function (renderer) { + renderer.setTextureProviderPrev(provider.key, provider); + return renderer; + }; + }) + .subscribe(this._glRendererOperation$); + this._setTileSizeSubscriptionPrev = this._container.renderService.size$ + .switchMap(function (size) { + return Observable_1.Observable + .combineLatest(textureProviderPrev$, Observable_1.Observable.of(size)) + .first(); + }) + .subscribe(function (_a) { + var provider = _a[0], size = _a[1]; + var viewportSize = Math.max(size.width, size.height); + var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512; + provider.setTileSize(tileSize); + }); + this._abortTextureProviderSubscriptionPrev = textureProviderPrev$ + .pairwise() + .subscribe(function (pair) { + var previous = pair[0]; + previous.abort(); + }); + var roiTriggerPrev$ = Observable_1.Observable + .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250)) + .map(function (_a) { + var camera = _a[0], size = _a[1]; + return [ + camera.camera.position.clone(), + camera.camera.lookat.clone(), + camera.zoom.valueOf(), + size.height.valueOf(), + size.width.valueOf() + ]; + }) + .pairwise() + .skipWhile(function (pls) { + return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0; + }) + .map(function (pls) { + var samePosition = pls[0][0].equals(pls[1][0]); + var sameLookat = pls[0][1].equals(pls[1][1]); + var sameZoom = pls[0][2] === pls[1][2]; + var sameHeight = pls[0][3] === pls[1][3]; + var sameWidth = pls[0][4] === pls[1][4]; + return samePosition && sameLookat && sameZoom && sameHeight && sameWidth; + }) + .distinctUntilChanged() + .filter(function (stalled) { + return stalled; + }) + .switchMap(function (stalled) { + return _this._container.renderService.renderCameraFrame$ + .first(); + }) + .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$); + this._setRegionOfInterestSubscriptionPrev = textureProviderPrev$ + .switchMap(function (provider) { + return roiTriggerPrev$ + .map(function (_a) { + var camera = _a[0], size = _a[1], transform = _a[2]; + return [ + _this._roiCalculator.computeRegionOfInterest(camera, size, transform), + provider, + ]; + }); + }) + .filter(function (args) { + return !args[1].disposed; + }) + .withLatestFrom(this._navigator.stateService.currentState$) + .subscribe(function (_a) { + var _b = _a[0], roi = _b[0], provider = _b[1], frame = _a[1]; + var shiftedRoi = null; + if (frame.state.previousNode.fullPano) { + if (frame.state.currentNode.fullPano) { + var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation); + var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation); + var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y); + var shift = directionDiff / (2 * Math.PI); + var bbox = { + maxX: _this._spatial.wrap(roi.bbox.maxX + shift, 0, 1), + maxY: roi.bbox.maxY, + minX: _this._spatial.wrap(roi.bbox.minX + shift, 0, 1), + minY: roi.bbox.minY, + }; + shiftedRoi = { + bbox: bbox, + pixelHeight: roi.pixelHeight, + pixelWidth: roi.pixelWidth, + }; + } + else { + var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation); + var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation); + var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y); + var shiftX = directionDiff / (2 * Math.PI); + var a1 = _this._spatial.angleToPlane(currentViewingDirection.toArray(), [0, 0, 1]); + var a2 = _this._spatial.angleToPlane(previousViewingDirection.toArray(), [0, 0, 1]); + var shiftY = (a2 - a1) / (2 * Math.PI); + var currentTransform = frame.state.currentTransform; + var size = Math.max(currentTransform.basicWidth, currentTransform.basicHeight); + var hFov = size > 0 ? + 2 * Math.atan(0.5 * currentTransform.basicWidth / (size * currentTransform.focal)) : + Math.PI / 3; + var vFov = size > 0 ? + 2 * Math.atan(0.5 * currentTransform.basicHeight / (size * currentTransform.focal)) : + Math.PI / 3; + var spanningWidth = hFov / (2 * Math.PI); + var spanningHeight = vFov / Math.PI; + var basicWidth = (roi.bbox.maxX - roi.bbox.minX) * spanningWidth; + var basicHeight = (roi.bbox.maxY - roi.bbox.minY) * spanningHeight; + var pixelWidth = roi.pixelWidth * spanningWidth; + var pixelHeight = roi.pixelHeight * spanningHeight; + var zoomShiftX = (roi.bbox.minX + roi.bbox.maxX) / 2 - 0.5; + var zoomShiftY = (roi.bbox.minY + roi.bbox.maxY) / 2 - 0.5; + var minX = 0.5 + shiftX + spanningWidth * zoomShiftX - basicWidth / 2; + var maxX = 0.5 + shiftX + spanningWidth * zoomShiftX + basicWidth / 2; + var minY = 0.5 + shiftY + spanningHeight * zoomShiftY - basicHeight / 2; + var maxY = 0.5 + shiftY + spanningHeight * zoomShiftY + basicHeight / 2; + var bbox = { + maxX: _this._spatial.wrap(maxX, 0, 1), + maxY: maxY, + minX: _this._spatial.wrap(minX, 0, 1), + minY: minY, + }; + shiftedRoi = { + bbox: bbox, + pixelHeight: pixelHeight, + pixelWidth: pixelWidth, + }; + } + } + else { + var currentBasicAspect = frame.state.currentTransform.basicAspect; + var previousBasicAspect = frame.state.previousTransform.basicAspect; + var _c = _this._getBasicCorners(currentBasicAspect, previousBasicAspect), _d = _c[0], cornerMinX = _d[0], cornerMinY = _d[1], _e = _c[1], cornerMaxX = _e[0], cornerMaxY = _e[1]; + var basicWidth = cornerMaxX - cornerMinX; + var basicHeight = cornerMaxY - cornerMinY; + var pixelWidth = roi.pixelWidth / basicWidth; + var pixelHeight = roi.pixelHeight / basicHeight; + var minX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.minX / basicWidth; + var maxX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.maxX / basicWidth; + var minY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.minY / basicHeight; + var maxY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.maxY / basicHeight; + var bbox = { + maxX: maxX, + maxY: maxY, + minX: minX, + minY: minY, + }; + _this._clipBoundingBox(bbox); + shiftedRoi = { + bbox: bbox, + pixelHeight: pixelHeight, + pixelWidth: pixelWidth, + }; + } + provider.setRegionOfInterest(shiftedRoi); + }); + var hasTexturePrev$ = textureProviderPrev$ + .switchMap(function (provider) { + return provider.hasTexture$; + }) + .startWith(false) + .publishReplay(1) + .refCount(); + this._hasTextureSubscriptionPrev = hasTexturePrev$.subscribe(function () { }); + var nodeImagePrev$ = this._navigator.stateService.currentState$ + .filter(function (frame) { + return frame.state.nodesAhead === 0 && !!frame.state.previousNode; + }) + .map(function (frame) { + return frame.state.previousNode; + }) + .distinctUntilChanged(undefined, function (node) { + return node.key; + }) + .debounceTime(1000) + .withLatestFrom(hasTexturePrev$) + .filter(function (args) { + return !args[1]; + }) + .map(function (args) { + return args[0]; + }) + .filter(function (node) { + return node.pano ? + Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize : + Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize; + }) + .switchMap(function (node) { + var baseImageSize = node.pano ? + Utils_1.Settings.basePanoramaSize : + Utils_1.Settings.baseImageSize; + if (Math.max(node.image.width, node.image.height) > baseImageSize) { + return Observable_1.Observable.empty(); + } + var image$ = node + .cacheImage$(Utils_1.Settings.maxImageSize) + .map(function (n) { + return [n.image, n]; + }); + return image$ + .takeUntil(hasTexturePrev$ + .filter(function (hasTexture) { + return hasTexture; + })) + .catch(function (error, caught) { + console.error("Failed to fetch high res image (" + node.key + ")", error); + return Observable_1.Observable.empty(); }); }) - .map(function (ed) { - var direction = ed[1]; - for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) { - var edge = _a[_i]; - if (edge.data.direction === direction) { - return edge.to; - } + .publish() + .refCount(); + this._updateBackgroundSubscriptionPrev = nodeImagePrev$ + .withLatestFrom(textureProviderPrev$) + .subscribe(function (args) { + if (args[0][1].key !== args[1].key || + args[1].disposed) { + return; } - return null; - }) - .filter(function (key) { - return key != null; - }) - .switchMap(function (key) { - return _this._navigator.graphService.cacheNode$(key); + args[1].updateBackground(args[0][0]); + }); + this._updateTextureImageSubscriptionPrev = nodeImagePrev$ + .map(function (imn) { + return function (renderer) { + renderer.updateTextureImage(imn[0], imn[1]); + return renderer; + }; }) - .subscribe(function (node) { - _this._navigator.stateService.appendNodes([node]); - }, function (error) { - console.error(error); - _this.stop(); + .subscribe(this._glRendererOperation$); + }; + SliderComponent.prototype._deactivate = function () { + var _this = this; + this._waitSubscription.unsubscribe(); + this._navigator.stateService.state$ + .first() + .subscribe(function (state) { + if (state !== State_1.State.Traversing) { + _this._navigator.stateService.traverse(); + } + }); + this._glRendererDisposer$.next(null); + this._domRenderer.deactivate(); + this._modeSubcription.unsubscribe(); + this._setKeysSubscription.unsubscribe(); + this._stateSubscription.unsubscribe(); + this._glRenderSubscription.unsubscribe(); + this._domRenderSubscription.unsubscribe(); + this._moveSubscription.unsubscribe(); + this.configure({ keys: null }); + }; + SliderComponent.prototype._getDefaultConfiguration = function () { + return { + initialPosition: 1, + mode: Component_1.SliderMode.Motion, + sliderVisible: true, + }; + }; + SliderComponent.prototype._catchCacheNode$ = function (key) { + return this._navigator.graphService.cacheNode$(key) + .catch(function (error, caught) { + console.error("Failed to cache slider node (" + key + ")", error); + return Observable_1.Observable.empty(); }); - this.fire(SequenceComponent.playingchanged, true); }; - SequenceComponent.prototype._stop = function () { - this._playingSubscription.unsubscribe(); - this._playingSubscription = null; - this.fire(SequenceComponent.playingchanged, false); + SliderComponent.prototype._getBasicCorners = function (currentAspect, previousAspect) { + var offsetX; + var offsetY; + if (currentAspect > previousAspect) { + offsetX = 0.5; + offsetY = 0.5 * currentAspect / previousAspect; + } + else { + offsetX = 0.5 * previousAspect / currentAspect; + offsetY = 0.5; + } + return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]]; }; - /** @inheritdoc */ - SequenceComponent.componentName = "sequence"; - /** - * Event fired when playing starts or stops. - * - * @event PlayerComponent#playingchanged - * @type {boolean} Indicates whether the player is playing. - */ - SequenceComponent.playingchanged = "playingchanged"; - return SequenceComponent; + SliderComponent.prototype._clipBoundingBox = function (bbox) { + bbox.minX = Math.max(0, Math.min(1, bbox.minX)); + bbox.maxX = Math.max(0, Math.min(1, bbox.maxX)); + bbox.minY = Math.max(0, Math.min(1, bbox.minY)); + bbox.maxY = Math.max(0, Math.min(1, bbox.maxY)); + }; + SliderComponent.componentName = "slider"; + return SliderComponent; }(Component_1.Component)); -exports.SequenceComponent = SequenceComponent; -Component_1.ComponentService.register(SequenceComponent); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SequenceComponent; +exports.SliderComponent = SliderComponent; +Component_1.ComponentService.register(SliderComponent); +exports.default = SliderComponent; -},{"../../Component":207,"../../Edge":208,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/of":44,"rxjs/add/operator/concat":50,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/finally":57,"rxjs/add/operator/first":58,"rxjs/add/operator/map":60,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/share":69,"rxjs/add/operator/switchMap":73,"rxjs/add/operator/takeUntil":75,"rxjs/add/operator/withLatestFrom":76}],246:[function(require,module,exports){ +},{"../../Component":290,"../../Geo":293,"../../Render":296,"../../State":297,"../../Tiles":299,"../../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34}],351:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -var SequenceDOMInteraction = (function () { - function SequenceDOMInteraction() { - this._mouseEnterDirection$ = new Subject_1.Subject(); - this._mouseLeaveDirection$ = new Subject_1.Subject(); +var Component_1 = require("../../Component"); +var SliderDOMRenderer = /** @class */ (function () { + function SliderDOMRenderer(container) { + this._container = container; + this._interacting = false; + this._notifyModeChanged$ = new Subject_1.Subject(); + this._notifyPositionChanged$ = new Subject_1.Subject(); + this._stopInteractionSubscription = null; } - Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", { + Object.defineProperty(SliderDOMRenderer.prototype, "mode$", { get: function () { - return this._mouseEnterDirection$; + return this._notifyModeChanged$; }, enumerable: true, configurable: true }); - Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", { + Object.defineProperty(SliderDOMRenderer.prototype, "position$", { get: function () { - return this._mouseLeaveDirection$; + return this._notifyPositionChanged$; }, enumerable: true, configurable: true }); - return SequenceDOMInteraction; + SliderDOMRenderer.prototype.activate = function () { + var _this = this; + if (!!this._stopInteractionSubscription) { + return; + } + this._stopInteractionSubscription = Observable_1.Observable + .merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$ + .filter(function (touchEvent) { + return touchEvent.touches.length === 0; + })) + .subscribe(function (event) { + if (_this._interacting) { + _this._interacting = false; + } + }); + }; + SliderDOMRenderer.prototype.deactivate = function () { + if (!this._stopInteractionSubscription) { + return; + } + this._interacting = false; + this._stopInteractionSubscription.unsubscribe(); + this._stopInteractionSubscription = null; + }; + SliderDOMRenderer.prototype.render = function (position, mode, motionless, pano, visible) { + var children = []; + if (visible) { + children.push(vd.h("div.SliderBorder", [])); + var modeVisible = !(motionless || pano); + if (modeVisible) { + children.push(this._createModeButton(mode)); + } + children.push(this._createPositionInput(position, modeVisible)); + } + var boundingRect = this._container.domContainer.getBoundingClientRect(); + var width = Math.max(215, Math.min(400, boundingRect.width - 100)); + return vd.h("div.SliderContainer", { style: { width: width + "px" } }, children); + }; + SliderDOMRenderer.prototype._createModeButton = function (mode) { + var _this = this; + var properties = { + onclick: function () { + _this._notifyModeChanged$.next(mode === Component_1.SliderMode.Motion ? + Component_1.SliderMode.Stationary : + Component_1.SliderMode.Motion); + }, + }; + var className = mode === Component_1.SliderMode.Stationary ? + "SliderModeButtonPressed" : + "SliderModeButton"; + return vd.h("div." + className, properties, [vd.h("div.SliderModeIcon", [])]); + }; + SliderDOMRenderer.prototype._createPositionInput = function (position, modeVisible) { + var _this = this; + var onChange = function (e) { + _this._notifyPositionChanged$.next(Number(e.target.value) / 1000); + }; + var onStart = function (e) { + _this._interacting = true; + e.stopPropagation(); + }; + var onMove = function (e) { + if (_this._interacting) { + e.stopPropagation(); + } + }; + var onKeyDown = function (e) { + if (e.key === "ArrowDown" || e.key === "ArrowLeft" || + e.key === "ArrowRight" || e.key === "ArrowUp") { + e.preventDefault(); + } + }; + var boundingRect = this._container.domContainer.getBoundingClientRect(); + var width = Math.max(215, Math.min(400, boundingRect.width - 105)) - 68 + (modeVisible ? 0 : 36); + var positionInput = vd.h("input.SliderPosition", { + max: 1000, + min: 0, + onchange: onChange, + oninput: onChange, + onkeydown: onKeyDown, + onmousedown: onStart, + onmousemove: onMove, + ontouchmove: onMove, + ontouchstart: onStart, + style: { + width: width + "px", + }, + type: "range", + value: 1000 * position, + }, []); + return vd.h("div.SliderPositionContainer", [positionInput]); + }; + return SliderDOMRenderer; }()); -exports.SequenceDOMInteraction = SequenceDOMInteraction; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SequenceDOMInteraction; +exports.SliderDOMRenderer = SliderDOMRenderer; +exports.default = SliderDOMRenderer; -},{"rxjs/Subject":33}],247:[function(require,module,exports){ -/// +},{"../../Component":290,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],352:[function(require,module,exports){ "use strict"; -var vd = require("virtual-dom"); -var Edge_1 = require("../../Edge"); -var SequenceDOMRenderer = (function () { - function SequenceDOMRenderer(element) { - this._minThresholdWidth = 320; - this._maxThresholdWidth = 1480; - this._minThresholdHeight = 240; - this._maxThresholdHeight = 820; +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../Component"); +var Geo_1 = require("../../Geo"); +var SliderGLRenderer = /** @class */ (function () { + function SliderGLRenderer() { + this._factory = new Component_1.MeshFactory(); + this._scene = new Component_1.MeshScene(); + this._spatial = new Geo_1.Spatial(); + this._currentKey = null; + this._previousKey = null; + this._disabled = false; + this._curtain = 1; + this._frameId = 0; + this._needsRender = false; + this._mode = null; + this._currentProviderDisposers = {}; + this._previousProviderDisposers = {}; } - SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) { - if (configuration.visible === false) { - return vd.h("div.SequenceContainer", {}, []); + Object.defineProperty(SliderGLRenderer.prototype, "disabled", { + get: function () { + return this._disabled; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SliderGLRenderer.prototype, "frameId", { + get: function () { + return this._frameId; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SliderGLRenderer.prototype, "needsRender", { + get: function () { + return this._needsRender; + }, + enumerable: true, + configurable: true + }); + SliderGLRenderer.prototype.setTextureProvider = function (key, provider) { + this._setTextureProvider(key, this._currentKey, provider, this._currentProviderDisposers, this._updateTexture.bind(this)); + }; + SliderGLRenderer.prototype.setTextureProviderPrev = function (key, provider) { + this._setTextureProvider(key, this._previousKey, provider, this._previousProviderDisposers, this._updateTexturePrev.bind(this)); + }; + SliderGLRenderer.prototype.update = function (frame, mode) { + this._updateFrameId(frame.id); + this._updateImagePlanes(frame.state, mode); + }; + SliderGLRenderer.prototype.updateCurtain = function (curtain) { + if (this._curtain === curtain) { + return; } - var nextKey = null; - var prevKey = null; - for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) { - var edge = _a[_i]; - if (edge.data.direction === Edge_1.EdgeDirection.Next) { - nextKey = edge.to; + this._curtain = curtain; + this._updateCurtain(); + this._needsRender = true; + }; + SliderGLRenderer.prototype.updateTexture = function (image, node) { + var imagePlanes = node.key === this._currentKey ? + this._scene.imagePlanes : + node.key === this._previousKey ? + this._scene.imagePlanesOld : + []; + if (imagePlanes.length === 0) { + return; + } + this._needsRender = true; + for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) { + var plane = imagePlanes_1[_i]; + var material = plane.material; + var texture = material.uniforms.projectorTex.value; + texture.image = image; + texture.needsUpdate = true; + } + }; + SliderGLRenderer.prototype.updateTextureImage = function (image, node) { + if (this._currentKey !== node.key) { + return; + } + this._needsRender = true; + for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) { + var plane = _a[_i]; + var material = plane.material; + var texture = material.uniforms.projectorTex.value; + texture.image = image; + texture.needsUpdate = true; + } + }; + SliderGLRenderer.prototype.render = function (perspectiveCamera, renderer) { + if (!this.disabled) { + renderer.render(this._scene.sceneOld, perspectiveCamera); + } + renderer.render(this._scene.scene, perspectiveCamera); + this._needsRender = false; + }; + SliderGLRenderer.prototype.dispose = function () { + this._scene.clear(); + for (var key in this._currentProviderDisposers) { + if (!this._currentProviderDisposers.hasOwnProperty(key)) { + continue; } - if (edge.data.direction === Edge_1.EdgeDirection.Prev) { - prevKey = edge.to; + this._currentProviderDisposers[key](); + } + for (var key in this._previousProviderDisposers) { + if (!this._previousProviderDisposers.hasOwnProperty(key)) { + continue; } + this._previousProviderDisposers[key](); } - var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component); - var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator); - var containerProperties = { - style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" }, - }; - return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton])); + this._currentProviderDisposers = {}; + this._previousProviderDisposers = {}; }; - SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) { - var elementWidth = element.offsetWidth; - var elementHeight = element.offsetHeight; - var minWidth = configuration.minWidth; - var maxWidth = configuration.maxWidth; - if (maxWidth < minWidth) { - maxWidth = minWidth; + SliderGLRenderer.prototype._getBasicCorners = function (currentAspect, previousAspect) { + var offsetX; + var offsetY; + if (currentAspect > previousAspect) { + offsetX = 0.5; + offsetY = 0.5 * currentAspect / previousAspect; } - var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth); - var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight); - var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight))); - return minWidth + coeff * (maxWidth - minWidth); + else { + offsetX = 0.5 * previousAspect / currentAspect; + offsetY = 0.5; + } + return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]]; }; - SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) { - var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null || - configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null; - var onclick = configuration.playing ? - function (e) { component.stop(); } : - canPlay ? function (e) { component.play(); } : null; - var buttonProperties = { - onclick: onclick, - style: {}, - }; - var iconClass = configuration.playing ? - "Stop" : - canPlay ? "Play" : "PlayDisabled"; - var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []); - var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled"; - return vd.h("div." + buttonClass, buttonProperties, [icon]); + SliderGLRenderer.prototype._setDisabled = function (state) { + this._disabled = state.currentNode == null || + state.previousNode == null || + (state.currentNode.pano && !state.currentNode.fullPano) || + (state.previousNode.pano && !state.previousNode.fullPano) || + (state.currentNode.fullPano && !state.previousNode.fullPano); }; - SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) { - var nextProperties = { - onclick: nextKey != null ? - function (e) { - navigator.moveDir$(Edge_1.EdgeDirection.Next) - .subscribe(function (node) { return; }, function (error) { console.error(error); }); - } : - null, - onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); }, - onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); }, - style: {}, - }; - var prevProperties = { - onclick: prevKey != null ? - function (e) { - navigator.moveDir$(Edge_1.EdgeDirection.Prev) - .subscribe(function (node) { return; }, function (error) { console.error(error); }); - } : - null, - onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); }, - onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); }, - style: {}, + SliderGLRenderer.prototype._setTextureProvider = function (key, originalKey, provider, providerDisposers, updateTexture) { + var _this = this; + if (key !== originalKey) { + return; + } + var createdSubscription = provider.textureCreated$ + .subscribe(updateTexture); + var updatedSubscription = provider.textureUpdated$ + .subscribe(function (updated) { + _this._needsRender = true; + }); + var dispose = function () { + createdSubscription.unsubscribe(); + updatedSubscription.unsubscribe(); + provider.dispose(); }; - var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey); - var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey); - var nextIcon = vd.h("div.SequenceComponentIcon", []); - var prevIcon = vd.h("div.SequenceComponentIcon", []); - return [ - vd.h("div." + nextClass, nextProperties, [nextIcon]), - vd.h("div." + prevClass, prevProperties, [prevIcon]), - ]; + if (key in providerDisposers) { + var disposeProvider = providerDisposers[key]; + disposeProvider(); + delete providerDisposers[key]; + } + providerDisposers[key] = dispose; + }; + SliderGLRenderer.prototype._updateCurtain = function () { + for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) { + var plane = _a[_i]; + var shaderMaterial = plane.material; + if (!!shaderMaterial.uniforms.curtain) { + shaderMaterial.uniforms.curtain.value = this._curtain; + } + } }; - SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) { - var className = direction === Edge_1.EdgeDirection.Next ? - "SequenceStepNext" : - "SequenceStepPrev"; - if (key == null) { - className += "Disabled"; + SliderGLRenderer.prototype._updateFrameId = function (frameId) { + this._frameId = frameId; + }; + SliderGLRenderer.prototype._updateImagePlanes = function (state, mode) { + var currentChanged = state.currentNode != null && this._currentKey !== state.currentNode.key; + var previousChanged = state.previousNode != null && this._previousKey !== state.previousNode.key; + var modeChanged = this._mode !== mode; + if (!(currentChanged || previousChanged || modeChanged)) { + return; + } + this._setDisabled(state); + this._needsRender = true; + this._mode = mode; + var motionless = state.motionless || mode === Component_1.SliderMode.Stationary || state.currentNode.pano; + if (this.disabled || previousChanged) { + if (this._previousKey in this._previousProviderDisposers) { + this._previousProviderDisposers[this._previousKey](); + delete this._previousProviderDisposers[this._previousKey]; + } + } + if (this.disabled) { + this._scene.setImagePlanesOld([]); } else { - if (highlightKey === key) { - className += "Highlight"; + if (previousChanged || modeChanged) { + var previousNode = state.previousNode; + this._previousKey = previousNode.key; + var elements = state.currentTransform.rt.elements; + var translation = [elements[12], elements[13], elements[14]]; + var currentAspect = state.currentTransform.basicAspect; + var previousAspect = state.previousTransform.basicAspect; + var textureScale = currentAspect > previousAspect ? + [1, previousAspect / currentAspect] : + [currentAspect / previousAspect, 1]; + var rotation = state.currentNode.rotation; + var width = state.currentNode.width; + var height = state.currentNode.height; + if (previousNode.fullPano) { + rotation = state.previousNode.rotation; + translation = this._spatial + .rotate(this._spatial + .opticalCenter(state.currentNode.rotation, translation) + .toArray(), rotation) + .multiplyScalar(-1) + .toArray(); + width = state.previousNode.width; + height = state.previousNode.height; + } + var transform = new Geo_1.Transform(state.currentNode.orientation, width, height, state.currentNode.focal, state.currentNode.scale, previousNode.gpano, rotation, translation, previousNode.image, textureScale); + var mesh = undefined; + if (previousNode.fullPano) { + mesh = this._factory.createMesh(previousNode, motionless || state.currentNode.fullPano ? transform : state.previousTransform); + } + else { + if (motionless) { + var _a = this._getBasicCorners(currentAspect, previousAspect), _b = _a[0], basicX0 = _b[0], basicY0 = _b[1], _c = _a[1], basicX1 = _c[0], basicY1 = _c[1]; + mesh = this._factory.createFlatMesh(state.previousNode, transform, basicX0, basicX1, basicY0, basicY1); + } + else { + mesh = this._factory.createMesh(state.previousNode, state.previousTransform); + } + } + this._scene.setImagePlanesOld([mesh]); } } - return className; + if (currentChanged) { + if (this._currentKey in this._currentProviderDisposers) { + this._currentProviderDisposers[this._currentKey](); + delete this._currentProviderDisposers[this._currentKey]; + } + this._currentKey = state.currentNode.key; + var imagePlane = state.currentNode.pano && !state.currentNode.fullPano ? + this._factory.createMesh(state.currentNode, state.currentTransform) : + this._factory.createCurtainMesh(state.currentNode, state.currentTransform); + this._scene.setImagePlanes([imagePlane]); + this._updateCurtain(); + } }; - return SequenceDOMRenderer; + SliderGLRenderer.prototype._updateTexture = function (texture) { + this._needsRender = true; + for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) { + var plane = _a[_i]; + var material = plane.material; + var oldTexture = material.uniforms.projectorTex.value; + material.uniforms.projectorTex.value = null; + oldTexture.dispose(); + material.uniforms.projectorTex.value = texture; + } + }; + SliderGLRenderer.prototype._updateTexturePrev = function (texture) { + this._needsRender = true; + for (var _i = 0, _a = this._scene.imagePlanesOld; _i < _a.length; _i++) { + var plane = _a[_i]; + var material = plane.material; + var oldTexture = material.uniforms.projectorTex.value; + material.uniforms.projectorTex.value = null; + oldTexture.dispose(); + material.uniforms.projectorTex.value = texture; + } + }; + return SliderGLRenderer; }()); -exports.SequenceDOMRenderer = SequenceDOMRenderer; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SequenceDOMRenderer; +exports.SliderGLRenderer = SliderGLRenderer; +exports.default = SliderGLRenderer; -},{"../../Edge":208,"virtual-dom":163}],248:[function(require,module,exports){ +},{"../../Component":290,"../../Geo":293}],353:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var GeometryTagError_1 = require("./error/GeometryTagError"); exports.GeometryTagError = GeometryTagError_1.GeometryTagError; var PointGeometry_1 = require("./geometry/PointGeometry"); @@ -22671,108 +31191,115 @@ var OutlineTag_1 = require("./tag/OutlineTag"); exports.OutlineTag = OutlineTag_1.OutlineTag; var SpotTag_1 = require("./tag/SpotTag"); exports.SpotTag = SpotTag_1.SpotTag; -var Alignment_1 = require("./tag/Alignment"); -exports.Alignment = Alignment_1.Alignment; var TagComponent_1 = require("./TagComponent"); exports.TagComponent = TagComponent_1.TagComponent; +var TagMode_1 = require("./TagMode"); +exports.TagMode = TagMode_1.TagMode; -},{"./TagComponent":249,"./error/GeometryTagError":255,"./geometry/PointGeometry":257,"./geometry/PolygonGeometry":258,"./geometry/RectGeometry":259,"./tag/Alignment":261,"./tag/OutlineTag":264,"./tag/SpotTag":267}],249:[function(require,module,exports){ -/// +},{"./TagComponent":354,"./TagMode":357,"./error/GeometryTagError":361,"./geometry/PointGeometry":363,"./geometry/PolygonGeometry":364,"./geometry/RectGeometry":365,"./tag/OutlineTag":377,"./tag/SpotTag":380}],354:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var THREE = require("three"); +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var when = require("when"); var Observable_1 = require("rxjs/Observable"); -var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/observable/empty"); -require("rxjs/add/observable/from"); -require("rxjs/add/observable/merge"); -require("rxjs/add/observable/of"); -require("rxjs/add/operator/combineLatest"); -require("rxjs/add/operator/concat"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/do"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/merge"); -require("rxjs/add/operator/mergeMap"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/share"); -require("rxjs/add/operator/skip"); -require("rxjs/add/operator/skipUntil"); -require("rxjs/add/operator/startWith"); -require("rxjs/add/operator/switchMap"); -require("rxjs/add/operator/take"); -require("rxjs/add/operator/takeUntil"); -require("rxjs/add/operator/withLatestFrom"); var Component_1 = require("../../Component"); +var Geo_1 = require("../../Geo"); var Render_1 = require("../../Render"); /** * @class TagComponent - * @classdesc Component for showing and editing tags with different geometries. + * + * @classdesc Component for showing and editing tags with different + * geometries composed from 2D basic image coordinates (see the + * {@link Viewer} class documentation for more information about coordinate + * systems). + * + * The `add` method is used for adding new tags or replacing + * tags already in the set. Tags are removed by id. + * + * If a tag already in the set has the same + * id as one of the tags added, the old tag will be removed and + * the added tag will take its place. + * + * The tag component mode can be set to either be non interactive or + * to be in creating mode of a certain geometry type. + * + * The tag properties can be updated at any time and the change will + * be visibile immediately. + * + * Tags are only relevant to a single image because they are based on + * 2D basic image coordinates. Tags related to a certain image should + * be removed when the viewer is moved to another node. + * + * To retrive and use the tag component + * + * @example + * ``` + * var viewer = new Mapillary.Viewer( + * "", + * "", + * "", + * { component: { tag: true } }); + * + * var tagComponent = viewer.getComponent("tag"); + * ``` */ -var TagComponent = (function (_super) { +var TagComponent = /** @class */ (function (_super) { __extends(TagComponent, _super); function TagComponent(name, container, navigator) { - var _this = this; - _super.call(this, name, container, navigator); - this._tagDomRenderer = new Component_1.TagDOMRenderer(); - this._tagSet = new Component_1.TagSet(); - this._tagCreator = new Component_1.TagCreator(); - this._tagGlRendererOperation$ = new Subject_1.Subject(); - this._tagGlRenderer$ = this._tagGlRendererOperation$ - .startWith(function (renderer) { - return renderer; - }) - .scan(function (renderer, operation) { - return operation(renderer); - }, new Component_1.TagGLRenderer()); - this._tags$ = this._tagSet.tagData$ - .map(function (tagData) { - var tags = []; + var _this = _super.call(this, name, container, navigator) || this; + _this._tagDomRenderer = new Component_1.TagDOMRenderer(); + _this._tagScene = new Component_1.TagScene(); + _this._tagSet = new Component_1.TagSet(); + _this._tagCreator = new Component_1.TagCreator(_this, navigator); + _this._viewportCoords = new Geo_1.ViewportCoords(); + _this._createHandlers = { + "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator), + "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator), + "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator), + "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator), + "Default": undefined, + }; + _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet); + _this._renderTags$ = _this._tagSet.changed$ + .map(function (tagSet) { + var tags = tagSet.getAll(); // ensure that tags are always rendered in the same order // to avoid hover tracking problems on first resize. - for (var _i = 0, _a = Object.keys(tagData).sort(); _i < _a.length; _i++) { - var key = _a[_i]; - tags.push(tagData[key]); - } - return tags; - }) - .share(); - this._renderTags$ = this.tags$ - .withLatestFrom(this._navigator.stateService.currentTransform$) - .map(function (args) { - var tags = args[0]; - var transform = args[1]; - var renderTags = tags - .map(function (tag) { - if (tag instanceof Component_1.OutlineTag) { - return new Component_1.OutlineRenderTag(tag, transform); + tags.sort(function (t1, t2) { + var id1 = t1.tag.id; + var id2 = t2.tag.id; + if (id1 < id2) { + return -1; } - else if (tag instanceof Component_1.SpotTag) { - return new Component_1.SpotRenderTag(tag, transform); + if (id1 > id2) { + return 1; } - throw new Error("Tag type not supported"); + return 0; }); - return renderTags; + return tags; }) .share(); - this._tagChanged$ = this._tags$ + _this._tagChanged$ = _this._renderTags$ .switchMap(function (tags) { return Observable_1.Observable .from(tags) .mergeMap(function (tag) { return Observable_1.Observable - .merge(tag.changed$, tag.geometryChanged$); + .merge(tag.tag.changed$, tag.tag.geometryChanged$); }); }) .share(); - this._renderTagGLChanged$ = this._renderTags$ + _this._renderTagGLChanged$ = _this._renderTags$ .switchMap(function (tags) { return Observable_1.Observable .from(tags) @@ -22781,348 +31308,274 @@ var TagComponent = (function (_super) { }); }) .share(); - this._tagInterationInitiated$ = this._renderTags$ - .switchMap(function (tags) { - return Observable_1.Observable - .from(tags) - .mergeMap(function (tag) { - return tag.interact$ - .map(function (interaction) { - return interaction.tag.id; - }); - }); - }) - .share(); - this._tagInteractionAbort$ = Observable_1.Observable - .merge(this._container.mouseService.mouseUp$, this._container.mouseService.mouseLeave$) - .map(function (e) { - return; - }) - .share(); - this._activeTag$ = this._renderTags$ - .switchMap(function (tags) { - return Observable_1.Observable - .from(tags) - .mergeMap(function (tag) { - return tag.interact$; - }); - }) - .merge(this._tagInteractionAbort$ - .map(function () { - return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null }; - })) - .share(); - this._createGeometryChanged$ = this._tagCreator.tag$ + _this._createGeometryChanged$ = _this._tagCreator.tag$ .switchMap(function (tag) { return tag != null ? tag.geometryChanged$ : Observable_1.Observable.empty(); }) .share(); - this._tagCreated$ = this._tagCreator.tag$ + _this._createGLObjectsChanged$ = _this._tagCreator.tag$ .switchMap(function (tag) { return tag != null ? - tag.created$ : + tag.glObjectsChanged$ : Observable_1.Observable.empty(); }) .share(); - this._vertexGeometryCreated$ = this._tagCreated$ - .map(function (tag) { - return tag.geometry; - }) - .share(); - this._pointGeometryCreated$ = new Subject_1.Subject(); - this._geometryCreated$ = Observable_1.Observable - .merge(this._vertexGeometryCreated$, this._pointGeometryCreated$) - .share(); - this._basicClick$ = this._container.mouseService.staticClick$ - .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) { - return [event, renderCamera, transform]; - }) - .map(function (ert) { - var event = ert[0]; - var camera = ert[1]; - var transform = ert[2]; - var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform); - return basic; - }) - .share(); - this._validBasicClick$ = this._basicClick$ - .filter(function (basic) { - var x = basic[0]; - var y = basic[1]; - return 0 <= x && x <= 1 && 0 <= y && y <= 1; - }) - .share(); - this._creatingConfiguration$ = this._configuration$ + _this._creatingConfiguration$ = _this._configuration$ .distinctUntilChanged(function (c1, c2) { - return c1.creating === c2.creating && c1.createType === c2.createType; + return c1.mode === c2.mode; }, function (configuration) { return { createColor: configuration.createColor, - createType: configuration.createType, - creating: configuration.creating, + mode: configuration.mode, }; }) .publishReplay(1) .refCount(); - this._creating$ = this._creatingConfiguration$ - .map(function (configuration) { - return configuration.creating; - }) - .publishReplay(1) - .refCount(); - this._creating$ - .subscribe(function (creating) { - _this.fire(TagComponent.creatingchanged, creating); + _this._creatingConfiguration$ + .subscribe(function (configuration) { + _this.fire(TagComponent.modechanged, configuration.mode); }); + return _this; } - Object.defineProperty(TagComponent.prototype, "tags$", { - /** - * Get tags observable. - * - * @description An observable emitting every time the items in the - * tag array changes. - * - * @returns {Observable} - */ - get: function () { - return this._tags$; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(TagComponent.prototype, "geometryCreated$", { - /** - * Get geometry created observable. - * - * @description An observable emitting every time a geometry - * has been created. - * - * @returns {Observable} - */ - get: function () { - return this._geometryCreated$; - }, - enumerable: true, - configurable: true - }); /** - * Set the tags to display. + * Add tags to the tag set or replace tags in the tag set. * - * @param {Tag[]} tags - The tags. + * @description If a tag already in the set has the same + * id as one of the tags added, the old tag will be removed + * the added tag will take its place. + * + * @param {Array} tags - Tags to add. + * + * @example ```tagComponent.add([tag1, tag2]);``` + */ + TagComponent.prototype.add = function (tags) { + var _this = this; + if (this._activated) { + this._navigator.stateService.currentTransform$ + .first() + .subscribe(function (transform) { + _this._tagSet.add(tags, transform); + var renderTags = tags + .map(function (tag) { + return _this._tagSet.get(tag.id); + }); + _this._tagScene.add(renderTags); + }); + } + else { + this._tagSet.addDeactivated(tags); + } + }; + /** + * Change the current tag mode. + * + * @description Change the tag mode to one of the create modes for creating new geometries. + * + * @param {TagMode} mode - New tag mode. + * + * @fires TagComponent#modechanged + * + * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);``` */ - TagComponent.prototype.setTags = function (tags) { - this._tagSet.set$.next(tags); + TagComponent.prototype.changeMode = function (mode) { + this.configure({ mode: mode }); }; /** - * Configure the component to enter create mode for - * creating a geometry of a certain type. + * Returns the tag in the tag set with the specified id, or + * undefined if the id matches no tag. * - * @description Supported geometry types are: rect + * @param {string} tagId - Id of the tag. * - * @param {string} geometryType - String specifying the geometry type. + * @example ```var tag = tagComponent.get("tagId");``` */ - TagComponent.prototype.startCreate = function (geometryType) { - this.configure({ createType: geometryType, creating: true }); + TagComponent.prototype.get = function (tagId) { + if (this._activated) { + var renderTag = this._tagSet.get(tagId); + return renderTag !== undefined ? renderTag.tag : undefined; + } + else { + return this._tagSet.getDeactivated(tagId); + } }; /** - * Configure the component to leave create mode. + * Returns an array of all tags. * - * @description A non completed geometry will be removed. + * @example ```var tags = tagComponent.getAll();``` */ - TagComponent.prototype.stopCreate = function () { - this.configure({ createType: null, creating: false }); + TagComponent.prototype.getAll = function () { + if (this.activated) { + return this._tagSet + .getAll() + .map(function (renderTag) { + return renderTag.tag; + }); + } + else { + return this._tagSet.getAllDeactivated(); + } }; - TagComponent.prototype._activate = function () { + /** + * Returns an array of tag ids for tags that contain the specified point. + * + * @description The pixel point must lie inside the polygon or rectangle + * of an added tag for the tag id to be returned. Tag ids for + * tags that do not have a fill will also be returned if the point is inside + * the geometry of the tag. Tags with point geometries can not be retrieved. + * + * No tag ids will be returned for panoramas. + * + * Notice that the pixelPoint argument requires x, y coordinates from pixel space. + * + * With this function, you can use the coordinates provided by mouse + * events to get information out of the tag component. + * + * If no tag at exist the pixel point, an empty array will be returned. + * + * @param {Array} pixelPoint - Pixel coordinates on the viewer element. + * @returns {Array} Ids of the tags that contain the specified pixel point. + * + * @example + * ``` + * tagComponent.getTagIdsAt([100, 100]) + * .then((tagIds) => { console.log(tagIds); }); + * ``` + */ + TagComponent.prototype.getTagIdsAt = function (pixelPoint) { var _this = this; - this._geometryCreatedEventSubscription = this._geometryCreated$ - .subscribe(function (geometry) { - _this.fire(TagComponent.geometrycreated, geometry); - }); - this._tagsChangedEventSubscription = this._tags$ - .subscribe(function (tags) { - _this.fire(TagComponent.tagschanged, tags); - }); - var nodeChanged$ = this.configuration$ - .switchMap(function (configuration) { - return configuration.creating ? - _this._navigator.stateService.currentNode$ - .skip(1) - .take(1) - .map(function (n) { return null; }) : - Observable_1.Observable.empty(); - }); - var tagAborted$ = this._tagCreator.tag$ - .switchMap(function (tag) { - return tag != null ? - tag.aborted$ - .map(function (t) { return null; }) : - Observable_1.Observable.empty(); - }); - var tagCreated$ = this._tagCreated$ - .map(function (t) { return null; }); - var pointGeometryCreated$ = this._pointGeometryCreated$ - .map(function (p) { return null; }); - this._stopCreateSubscription = Observable_1.Observable - .merge(nodeChanged$, tagAborted$, tagCreated$, pointGeometryCreated$) - .subscribe(function () { _this.stopCreate(); }); - this._creatorConfigurationSubscription = this._configuration$ - .subscribe(this._tagCreator.configuration$); - this._createSubscription = this._creatingConfiguration$ - .switchMap(function (configuration) { - return configuration.creating && - configuration.createType === "rect" || - configuration.createType === "polygon" ? - _this._validBasicClick$.take(1) : - Observable_1.Observable.empty(); - }) - .subscribe(this._tagCreator.create$); - this._createPointSubscription = this._creatingConfiguration$ - .switchMap(function (configuration) { - return configuration.creating && - configuration.createType === "point" ? - _this._validBasicClick$.take(1) : - Observable_1.Observable.empty(); - }) - .map(function (basic) { - return new Component_1.PointGeometry(basic); - }) - .subscribe(this._pointGeometryCreated$); - this._setCreateVertexSubscription = Observable_1.Observable - .combineLatest(this._container.mouseService.mouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$) - .filter(function (etr) { - return etr[1] != null; - }) - .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) { - return [etr[0], etr[1], etr[2], transform]; - }) - .subscribe(function (etrt) { - var event = etrt[0]; - var tag = etrt[1]; - var camera = etrt[2]; - var transform = etrt[3]; - var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform); - if (tag.geometry instanceof Component_1.RectGeometry) { - tag.geometry.setVertex2d(3, basic, transform); - } - else if (tag.geometry instanceof Component_1.PolygonGeometry) { - tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform); - } - }); - this._addPointSubscription = this._creatingConfiguration$ - .switchMap(function (configuration) { - var createType = configuration.createType; - return configuration.creating && - (createType === "rect" || createType === "polygon") ? - _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) : - Observable_1.Observable.empty(); - }) - .withLatestFrom(this._tagCreator.tag$, function (basic, tag) { - return [basic, tag]; - }) - .subscribe(function (bt) { - var basic = bt[0]; - var tag = bt[1]; - tag.addPoint(basic); - }); - this._deleteCreatedSubscription = this._creating$ - .subscribe(function (creating) { - _this._tagCreator.delete$.next(null); + return when.promise(function (resolve, reject) { + _this._container.renderService.renderCamera$ + .first() + .map(function (render) { + var viewport = _this._viewportCoords + .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element); + var ids = _this._tagScene.intersectObjects(viewport, render.perspective); + return ids; + }) + .subscribe(function (ids) { + resolve(ids); + }, function (error) { + reject(error); + }); }); - this._setGLCreateTagSubscription = Observable_1.Observable - .merge(this._tagCreator.tag$, this._createGeometryChanged$) - .withLatestFrom(this._navigator.stateService.currentTransform$, function (tag, transform) { - return [tag, transform]; + }; + /** + * Check if a tag exist in the tag set. + * + * @param {string} tagId - Id of the tag. + * + * @example ```var tagExists = tagComponent.has("tagId");``` + */ + TagComponent.prototype.has = function (tagId) { + return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId); + }; + /** + * Remove tags with the specified ids from the tag set. + * + * @param {Array} tagIds - Ids for tags to remove. + * + * @example ```tagComponent.remove(["id-1", "id-2"]);``` + */ + TagComponent.prototype.remove = function (tagIds) { + if (this._activated) { + this._tagSet.remove(tagIds); + this._tagScene.remove(tagIds); + } + else { + this._tagSet.removeDeactivated(tagIds); + } + }; + /** + * Remove all tags from the tag set. + * + * @example ```tagComponent.removeAll();``` + */ + TagComponent.prototype.removeAll = function () { + if (this._activated) { + this._tagSet.removeAll(); + this._tagScene.removeAll(); + } + else { + this._tagSet.removeAllDeactivated(); + } + }; + TagComponent.prototype._activate = function () { + var _this = this; + this._editVertexHandler.enable(); + var handlerGeometryCreated$ = Observable_1.Observable + .from(Object.keys(this._createHandlers)) + .map(function (key) { + return _this._createHandlers[key]; }) - .map(function (tt) { - return function (renderer) { - var tag = tt[0]; - var transform = tt[1]; - if (tag == null) { - renderer.removeCreateTag(); - } - else { - renderer.setCreateTag(tag, transform); - } - return renderer; - }; + .filter(function (handler) { + return !!handler; }) - .subscribe(this._tagGlRendererOperation$); - this._claimMouseSubscription = this._tagInterationInitiated$ - .switchMap(function (id) { - return _this._container.mouseService.mouseMove$ - .takeUntil(_this._tagInteractionAbort$) - .take(1); + .mergeMap(function (handler) { + return handler.geometryCreated$; }) - .subscribe(function (e) { - _this._container.mouseService.claimMouse(_this._name, 1); + .share(); + this._fireGeometryCreatedSubscription = handlerGeometryCreated$ + .subscribe(function (geometry) { + _this.fire(TagComponent.geometrycreated, geometry); }); - this._mouseDragSubscription = this._activeTag$ - .withLatestFrom(this._container.mouseService.mouseMove$, function (a, e) { - return [a, e]; + this._fireCreateGeometryEventSubscription = this._tagCreator.tag$ + .skipWhile(function (tag) { + return tag == null; }) - .switchMap(function (args) { - var activeTag = args[0]; - var mouseMove = args[1]; - if (activeTag.operation === Component_1.TagOperation.None) { - return Observable_1.Observable.empty(); + .distinctUntilChanged() + .subscribe(function (tag) { + var eventType = tag != null ? + TagComponent.creategeometrystart : + TagComponent.creategeometryend; + _this.fire(eventType, _this); + }); + this._handlerStopCreateSubscription = handlerGeometryCreated$ + .subscribe(function () { + _this.changeMode(Component_1.TagMode.Default); + }); + this._handlerEnablerSubscription = this._creatingConfiguration$ + .subscribe(function (configuration) { + _this._disableCreateHandlers(); + var mode = Component_1.TagMode[configuration.mode]; + var handler = _this._createHandlers[mode]; + if (!!handler) { + handler.enable(); } - var mouseDrag$ = Observable_1.Observable - .of(mouseMove) - .concat(_this._container.mouseService.filtered$(_this._name, _this._container.mouseService.mouseDrag$)); - return Observable_1.Observable - .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$) - .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) { - return [ec[0], ec[1], a, t]; - }); + }); + this._fireTagsChangedSubscription = this._renderTags$ + .subscribe(function (tags) { + _this.fire(TagComponent.tagschanged, _this); + }); + this._stopCreateSubscription = this._tagCreator.tag$ + .switchMap(function (tag) { + return tag != null ? + tag.aborted$ + .map(function (t) { return null; }) : + Observable_1.Observable.empty(); }) - .subscribe(function (args) { - var mouseEvent = args[0]; - var renderCamera = args[1]; - var activeTag = args[2]; - var transform = args[3]; - if (activeTag.operation === Component_1.TagOperation.None) { - return; + .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); }); + this._setGLCreateTagSubscription = this._tagCreator.tag$ + .subscribe(function (tag) { + if (_this._tagScene.hasCreateTag()) { + _this._tagScene.removeCreateTag(); } - var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY); - if (activeTag.operation === Component_1.TagOperation.Centroid) { - activeTag.tag.geometry.setCentroid2d(basic, transform); - } - else if (activeTag.operation === Component_1.TagOperation.Vertex) { - var vertexGeometry = activeTag.tag.geometry; - vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform); + if (tag != null) { + _this._tagScene.addCreateTag(tag); } }); - this._unclaimMouseSubscription = this._container.mouseService - .filtered$(this._name, this._container.mouseService.mouseDragEnd$) - .subscribe(function (e) { - _this._container.mouseService.unclaimMouse(_this._name); + this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$ + .subscribe(function (tag) { + _this._tagScene.updateCreateTagObjects(tag); + }); + this._updateGLObjectsSubscription = this._renderTagGLChanged$ + .subscribe(function (tag) { + _this._tagScene.updateObjects(tag); + }); + this._updateTagSceneSubscription = this._tagChanged$ + .subscribe(function (tag) { + _this._tagScene.update(); }); - this._setTagsSubscription = this._renderTags$ - .map(function (tags) { - return function (renderer) { - renderer.setTags(tags); - return renderer; - }; - }) - .subscribe(this._tagGlRendererOperation$); - this._updateGLTagSubscription = this._renderTagGLChanged$ - .map(function (tag) { - return function (renderer) { - renderer.updateTag(tag); - return renderer; - }; - }) - .subscribe(this._tagGlRendererOperation$); - this._setNeedsRenderSubscription = this._tagChanged$ - .map(function (tag) { - return function (renderer) { - renderer.setNeedsRender(); - return renderer; - }; - }) - .subscribe(this._tagGlRendererOperation$); this._domSubscription = this._renderTags$ .startWith([]) .do(function (tags) { @@ -23131,158 +31584,198 @@ var TagComponent = (function (_super) { vnode: _this._tagDomRenderer.clear(), }); }) - .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), this._configuration$, function (renderTags, rc, atlas, tag, ct, c) { - return [rc, atlas, renderTags, tag, ct, c]; - }) - .withLatestFrom(this._navigator.stateService.currentTransform$, function (args, transform) { - return [args[0], args[1], args[2], args[3], args[4], args[5], transform]; + .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._container.renderService.size$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), function (renderTags, rc, atlas, size, tag, ct) { + return [rc, atlas, size, renderTags, tag, ct]; }) .map(function (args) { return { name: _this._name, - vnode: _this._tagDomRenderer.render(args[2], args[4], args[1], args[0].perspective, args[6], args[5]), + vnode: _this._tagDomRenderer.render(args[3], args[5], args[1], args[0].perspective, args[2]), }; }) .subscribe(this._container.domRenderer.render$); this._glSubscription = this._navigator.stateService.currentState$ - .withLatestFrom(this._tagGlRenderer$, function (frame, renderer) { - return [frame, renderer]; - }) - .map(function (fr) { - var frame = fr[0]; - var renderer = fr[1]; + .map(function (frame) { + var tagScene = _this._tagScene; return { name: _this._name, render: { frameId: frame.id, - needsRender: renderer.needsRender, - render: renderer.render.bind(renderer), + needsRender: tagScene.needsRender, + render: tagScene.render.bind(tagScene), stage: Render_1.GLRenderStage.Foreground, }, }; }) .subscribe(this._container.glRenderer.render$); + this._navigator.stateService.currentTransform$ + .first() + .subscribe(function (transform) { + _this._tagSet.activate(transform); + _this._tagScene.add(_this._tagSet.getAll()); + }); }; TagComponent.prototype._deactivate = function () { - this._tagGlRendererOperation$ - .next(function (renderer) { - renderer.dispose(); - return renderer; - }); - this._tagSet.set$.next([]); + this._editVertexHandler.disable(); + this._disableCreateHandlers(); + this._tagScene.clear(); + this._tagSet.deactivate(); this._tagCreator.delete$.next(null); - this._claimMouseSubscription.unsubscribe(); - this._mouseDragSubscription.unsubscribe(); - this._unclaimMouseSubscription.unsubscribe(); - this._setTagsSubscription.unsubscribe(); - this._updateGLTagSubscription.unsubscribe(); - this._setNeedsRenderSubscription.unsubscribe(); + this._updateGLObjectsSubscription.unsubscribe(); + this._updateTagSceneSubscription.unsubscribe(); this._stopCreateSubscription.unsubscribe(); - this._creatorConfigurationSubscription.unsubscribe(); - this._createSubscription.unsubscribe(); - this._createPointSubscription.unsubscribe(); - this._setCreateVertexSubscription.unsubscribe(); - this._addPointSubscription.unsubscribe(); - this._deleteCreatedSubscription.unsubscribe(); this._setGLCreateTagSubscription.unsubscribe(); + this._createGLObjectsChangedSubscription.unsubscribe(); this._domSubscription.unsubscribe(); this._glSubscription.unsubscribe(); - this._geometryCreatedEventSubscription.unsubscribe(); - this._tagsChangedEventSubscription.unsubscribe(); + this._fireCreateGeometryEventSubscription.unsubscribe(); + this._fireGeometryCreatedSubscription.unsubscribe(); + this._fireTagsChangedSubscription.unsubscribe(); + this._handlerStopCreateSubscription.unsubscribe(); + this._handlerEnablerSubscription.unsubscribe(); + this._container.element.classList.remove("component-tag-create"); }; TagComponent.prototype._getDefaultConfiguration = function () { return { createColor: 0xFFFFFF, - creating: false, + mode: Component_1.TagMode.Default, }; }; - TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) { - offsetX = offsetX != null ? offsetX : 0; - offsetY = offsetY != null ? offsetY : 0; - var clientRect = element.getBoundingClientRect(); - var canvasX = event.clientX - clientRect.left - offsetX; - var canvasY = event.clientY - clientRect.top - offsetY; - var projectedX = 2 * canvasX / element.offsetWidth - 1; - var projectedY = 1 - 2 * canvasY / element.offsetHeight; - var unprojected = new THREE.Vector3(projectedX, projectedY, 1).unproject(camera.perspective); - var basic = transform.projectBasic(unprojected.toArray()); - return basic; + TagComponent.prototype._disableCreateHandlers = function () { + var createHandlers = this._createHandlers; + for (var key in createHandlers) { + if (!createHandlers.hasOwnProperty(key)) { + continue; + } + var handler = createHandlers[key]; + if (!!handler) { + handler.disable(); + } + } }; /** @inheritdoc */ TagComponent.componentName = "tag"; /** - * Event fired when creation starts and stops. + * Event fired when an interaction to create a geometry ends. + * + * @description A create interaction can by a geometry being created + * or by the creation being aborted. + * + * @event TagComponent#creategeometryend + * @type {TagComponent} Tag component. + * @example + * ``` + * tagComponent.on("creategeometryend", function(component) { + * console.log(component); + * }); + * ``` + */ + TagComponent.creategeometryend = "creategeometryend"; + /** + * Event fired when an interaction to create a geometry starts. * - * @event TagComponent#creatingchanged - * @type {boolean} Indicates whether the component is creating a tag. + * @description A create interaction starts when the first vertex + * is created in the geometry. + * + * @event TagComponent#creategeometrystart + * @type {TagComponent} Tag component. + * @example + * ``` + * tagComponent.on("creategeometrystart", function(component) { + * console.log(component); + * }); + * ``` + */ + TagComponent.creategeometrystart = "creategeometrystart"; + /** + * Event fired when the create mode is changed. + * + * @event TagComponent#modechanged + * @type {TagMode} Tag mode + * @example + * ``` + * tagComponent.on("modechanged", function(mode) { + * console.log(mode); + * }); + * ``` */ - TagComponent.creatingchanged = "creatingchanged"; + TagComponent.modechanged = "modechanged"; /** * Event fired when a geometry has been created. * * @event TagComponent#geometrycreated * @type {Geometry} Created geometry. + * @example + * ``` + * tagComponent.on("geometrycreated", function(geometry) { + * console.log(geometry); + * }); + * ``` */ TagComponent.geometrycreated = "geometrycreated"; /** * Event fired when the tags collection has changed. * * @event TagComponent#tagschanged - * @type {Array} Current array of tags. + * @type {TagComponent} Tag component. + * @example + * ``` + * tagComponent.on("tagschanged", function(component) { + * console.log(component.getAll()); + * }); + * ``` */ TagComponent.tagschanged = "tagschanged"; return TagComponent; }(Component_1.Component)); exports.TagComponent = TagComponent; Component_1.ComponentService.register(TagComponent); -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = TagComponent; -},{"../../Component":207,"../../Render":213,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/empty":39,"rxjs/add/observable/from":40,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":49,"rxjs/add/operator/concat":50,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/do":54,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/merge":61,"rxjs/add/operator/mergeMap":63,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/share":69,"rxjs/add/operator/skip":70,"rxjs/add/operator/skipUntil":71,"rxjs/add/operator/startWith":72,"rxjs/add/operator/switchMap":73,"rxjs/add/operator/take":74,"rxjs/add/operator/takeUntil":75,"rxjs/add/operator/withLatestFrom":76,"three":157}],250:[function(require,module,exports){ +},{"../../Component":290,"../../Geo":293,"../../Render":296,"rxjs/Observable":29,"when":287}],355:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/share"); -require("rxjs/add/operator/withLatestFrom"); var Component_1 = require("../../Component"); -var TagCreator = (function () { - function TagCreator() { +var TagCreator = /** @class */ (function () { + function TagCreator(component, navigator) { + this._component = component; + this._navigator = navigator; this._tagOperation$ = new Subject_1.Subject(); - this._create$ = new Subject_1.Subject(); + this._createPolygon$ = new Subject_1.Subject(); + this._createRect$ = new Subject_1.Subject(); this._delete$ = new Subject_1.Subject(); - this._configuration$ = new Subject_1.Subject(); this._tag$ = this._tagOperation$ .scan(function (tag, operation) { return operation(tag); }, null) .share(); - this._create$ - .withLatestFrom(this._configuration$, function (coordinate, type) { - return [coordinate, type]; + this._createRect$ + .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$) + .map(function (_a) { + var coord = _a[0], conf = _a[1], transform = _a[2]; + return function (tag) { + var geometry = new Component_1.RectGeometry([ + coord[0], + coord[1], + coord[0], + coord[1], + ]); + return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform); + }; }) - .map(function (ct) { + .subscribe(this._tagOperation$); + this._createPolygon$ + .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$) + .map(function (_a) { + var coord = _a[0], conf = _a[1], transform = _a[2]; return function (tag) { - var coordinate = ct[0]; - var configuration = ct[1]; - if (configuration.createType === "rect") { - var geometry = new Component_1.RectGeometry([ - coordinate[0], - coordinate[1], - coordinate[0], - coordinate[1], - ]); - return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor }); - } - else if (configuration.createType === "polygon") { - var geometry = new Component_1.PolygonGeometry([ - [coordinate[0], coordinate[1]], - [coordinate[0], coordinate[1]], - [coordinate[0], coordinate[1]], - ]); - return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor }); - } - return null; + var geometry = new Component_1.PolygonGeometry([ + [coord[0], coord[1]], + [coord[0], coord[1]], + [coord[0], coord[1]], + ]); + return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform); }; }) .subscribe(this._tagOperation$); @@ -23294,23 +31787,23 @@ var TagCreator = (function () { }) .subscribe(this._tagOperation$); } - Object.defineProperty(TagCreator.prototype, "create$", { + Object.defineProperty(TagCreator.prototype, "createRect$", { get: function () { - return this._create$; + return this._createRect$; }, enumerable: true, configurable: true }); - Object.defineProperty(TagCreator.prototype, "delete$", { + Object.defineProperty(TagCreator.prototype, "createPolygon$", { get: function () { - return this._delete$; + return this._createPolygon$; }, enumerable: true, configurable: true }); - Object.defineProperty(TagCreator.prototype, "configuration$", { + Object.defineProperty(TagCreator.prototype, "delete$", { get: function () { - return this._configuration$; + return this._delete$; }, enumerable: true, configurable: true @@ -23325,34 +31818,26 @@ var TagCreator = (function () { return TagCreator; }()); exports.TagCreator = TagCreator; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = TagCreator; -},{"../../Component":207,"rxjs/Subject":33,"rxjs/add/operator/map":60,"rxjs/add/operator/scan":68,"rxjs/add/operator/share":69,"rxjs/add/operator/withLatestFrom":76}],251:[function(require,module,exports){ -/// +},{"../../Component":290,"rxjs/Subject":34}],356:[function(require,module,exports){ "use strict"; -var THREE = require("three"); +/// +Object.defineProperty(exports, "__esModule", { value: true }); var vd = require("virtual-dom"); -var TagDOMRenderer = (function () { +var TagDOMRenderer = /** @class */ (function () { function TagDOMRenderer() { } - TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, transform, configuration) { - var matrixWorldInverse = new THREE.Matrix4().getInverse(camera.matrixWorld); - var projectionMatrix = camera.projectionMatrix; + TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) { var vNodes = []; for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) { var tag = tags_1[_i]; - vNodes = vNodes.concat(tag.getDOMObjects(atlas, matrixWorldInverse, projectionMatrix)); + vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size)); } if (createTag != null) { - vNodes = vNodes.concat(createTag.getDOMObjects(transform, matrixWorldInverse, projectionMatrix)); + vNodes = vNodes.concat(createTag.getDOMObjects(camera, size)); } - var properties = { - style: { - "pointer-events": configuration.creating ? "all" : "none", - }, - }; - return vd.h("div.TagContainer", properties, vNodes); + return vd.h("div.TagContainer", {}, vNodes); }; TagDOMRenderer.prototype.clear = function () { return vd.h("div", {}, []); @@ -23361,191 +31846,409 @@ var TagDOMRenderer = (function () { }()); exports.TagDOMRenderer = TagDOMRenderer; -},{"three":157,"virtual-dom":163}],252:[function(require,module,exports){ -/// +},{"virtual-dom":246}],357:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Enumeration for tag modes + * @enum {number} + * @readonly + * @description Modes for the interaction in the tag component. + */ +var TagMode; +(function (TagMode) { + /** + * Disables creating tags. + */ + TagMode[TagMode["Default"] = 0] = "Default"; + /** + * Create a point geometry through a click. + */ + TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint"; + /** + * Create a polygon geometry through clicks. + */ + TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon"; + /** + * Create a rect geometry through clicks. + */ + TagMode[TagMode["CreateRect"] = 3] = "CreateRect"; + /** + * Create a rect geometry through drag. + * + * @description Claims the mouse which results in mouse handlers like + * drag pan and scroll zoom becoming inactive. + */ + TagMode[TagMode["CreateRectDrag"] = 4] = "CreateRectDrag"; +})(TagMode = exports.TagMode || (exports.TagMode = {})); +exports.default = TagMode; + +},{}],358:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var TagOperation; +(function (TagOperation) { + TagOperation[TagOperation["None"] = 0] = "None"; + TagOperation[TagOperation["Centroid"] = 1] = "Centroid"; + TagOperation[TagOperation["Vertex"] = 2] = "Vertex"; +})(TagOperation = exports.TagOperation || (exports.TagOperation = {})); +exports.default = TagOperation; + +},{}],359:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); -var TagGLRenderer = (function () { - function TagGLRenderer() { - this._scene = new THREE.Scene(); - this._tags = {}; +var TagScene = /** @class */ (function () { + function TagScene(scene, raycaster) { this._createTag = null; this._needsRender = false; + this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster(); + this._scene = !!scene ? scene : new THREE.Scene(); + this._objectTags = {}; + this._retrievableObjects = []; + this._tags = {}; } - Object.defineProperty(TagGLRenderer.prototype, "needsRender", { + Object.defineProperty(TagScene.prototype, "needsRender", { get: function () { return this._needsRender; }, enumerable: true, configurable: true }); - TagGLRenderer.prototype.render = function (perspectiveCamera, renderer) { + TagScene.prototype.add = function (tags) { + for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) { + var tag = tags_1[_i]; + if (tag.tag.id in this._tags) { + this._remove(tag.tag.id); + } + this._add(tag); + } + this._needsRender = true; + }; + TagScene.prototype.addCreateTag = function (tag) { + for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) { + var object = _a[_i]; + this._scene.add(object); + } + this._createTag = { tag: tag, objects: tag.glObjects }; + this._needsRender = true; + }; + TagScene.prototype.clear = function () { + for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) { + var id = _a[_i]; + this._remove(id); + } + this._needsRender = false; + }; + TagScene.prototype.get = function (id) { + return this.has(id) ? this._tags[id].tag : undefined; + }; + TagScene.prototype.has = function (id) { + return id in this._tags; + }; + TagScene.prototype.hasCreateTag = function () { + return this._createTag != null; + }; + TagScene.prototype.intersectObjects = function (_a, camera) { + var viewportX = _a[0], viewportY = _a[1]; + this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera); + var intersects = this._raycaster.intersectObjects(this._retrievableObjects); + var intersectedIds = []; + for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) { + var intersect = intersects_1[_i]; + if (intersect.object.uuid in this._objectTags) { + intersectedIds.push(this._objectTags[intersect.object.uuid]); + } + } + return intersectedIds; + }; + TagScene.prototype.remove = function (ids) { + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + this._remove(id); + } + this._needsRender = true; + }; + TagScene.prototype.removeAll = function () { + for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) { + var id = _a[_i]; + this._remove(id); + } + this._needsRender = true; + }; + TagScene.prototype.removeCreateTag = function () { + if (this._createTag == null) { + return; + } + for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) { + var object = _a[_i]; + this._scene.remove(object); + } + this._createTag.tag.dispose(); + this._createTag = null; + this._needsRender = true; + }; + TagScene.prototype.render = function (perspectiveCamera, renderer) { renderer.render(this._scene, perspectiveCamera); this._needsRender = false; }; - TagGLRenderer.prototype.setCreateTag = function (tag, transform) { - this._disposeCreateTag(); - this._addCreateTag(tag, transform); + TagScene.prototype.update = function () { + this._needsRender = true; + }; + TagScene.prototype.updateCreateTagObjects = function (tag) { + if (this._createTag.tag !== tag) { + throw new Error("Create tags do not have the same reference."); + } + for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) { + var object = _a[_i]; + this._scene.remove(object); + } + for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) { + var object = _c[_b]; + this._scene.add(object); + } + this._createTag.objects = tag.glObjects; this._needsRender = true; }; - TagGLRenderer.prototype.removeCreateTag = function () { - this._disposeCreateTag(); + TagScene.prototype.updateObjects = function (tag) { + var id = tag.tag.id; + if (this._tags[id].tag !== tag) { + throw new Error("Tags do not have the same reference."); + } + var tagObjects = this._tags[id]; + this._removeObjects(tagObjects); + delete this._tags[id]; + this._add(tag); this._needsRender = true; }; - TagGLRenderer.prototype.setTags = function (tags) { - this._disposeTags(); + TagScene.prototype._add = function (tag) { + var id = tag.tag.id; + var tagObjects = { tag: tag, objects: [], retrievableObjects: [] }; + this._tags[id] = tagObjects; + for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) { + var object = _a[_i]; + tagObjects.objects.push(object); + this._scene.add(object); + } + for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) { + var retrievableObject = _c[_b]; + tagObjects.retrievableObjects.push(retrievableObject); + this._retrievableObjects.push(retrievableObject); + this._objectTags[retrievableObject.uuid] = tag.tag.id; + } + }; + TagScene.prototype._remove = function (id) { + var tagObjects = this._tags[id]; + this._removeObjects(tagObjects); + tagObjects.tag.dispose(); + delete this._tags[id]; + }; + TagScene.prototype._removeObjects = function (tagObjects) { + for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) { + var object = _a[_i]; + this._scene.remove(object); + } + for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) { + var retrievableObject = _c[_b]; + var index = this._retrievableObjects.indexOf(retrievableObject); + if (index !== -1) { + this._retrievableObjects.splice(index, 1); + } + } + }; + return TagScene; +}()); +exports.TagScene = TagScene; +exports.default = TagScene; + +},{"three":240}],360:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Subject_1 = require("rxjs/Subject"); +var Component_1 = require("../../Component"); +var TagSet = /** @class */ (function () { + function TagSet() { + this._active = false; + this._hash = {}; + this._hashDeactivated = {}; + this._notifyChanged$ = new Subject_1.Subject(); + } + Object.defineProperty(TagSet.prototype, "active", { + get: function () { + return this._active; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TagSet.prototype, "changed$", { + get: function () { + return this._notifyChanged$; + }, + enumerable: true, + configurable: true + }); + TagSet.prototype.activate = function (transform) { + if (this._active) { + return; + } + for (var id in this._hashDeactivated) { + if (!this._hashDeactivated.hasOwnProperty(id)) { + continue; + } + var tag = this._hashDeactivated[id]; + this._add(tag, transform); + } + this._hashDeactivated = {}; + this._active = true; + this._notifyChanged$.next(this); + }; + TagSet.prototype.deactivate = function () { + if (!this._active) { + return; + } + for (var id in this._hash) { + if (!this._hash.hasOwnProperty(id)) { + continue; + } + this._hashDeactivated[id] = this._hash[id].tag; + } + this._hash = {}; + this._active = false; + }; + TagSet.prototype.add = function (tags, transform) { + this._assertActivationState(true); for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) { var tag = tags_1[_i]; - this._addTag(tag); + this._add(tag, transform); } - this._needsRender = true; + this._notifyChanged$.next(this); }; - TagGLRenderer.prototype.updateTag = function (tag) { - for (var _i = 0, _a = this._tags[tag.tag.id][1]; _i < _a.length; _i++) { - var object3d = _a[_i]; - this._scene.remove(object3d); + TagSet.prototype.addDeactivated = function (tags) { + this._assertActivationState(false); + for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) { + var tag = tags_2[_i]; + if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) { + throw new Error("Tag type not supported"); + } + this._hashDeactivated[tag.id] = tag; } - this._addTag(tag); }; - TagGLRenderer.prototype.setNeedsRender = function () { - this._needsRender = true; + TagSet.prototype.get = function (id) { + return this.has(id) ? this._hash[id] : undefined; }; - TagGLRenderer.prototype.dispose = function () { - this._disposeTags(); - this._disposeCreateTag(); - this._needsRender = false; + TagSet.prototype.getAll = function () { + var hash = this._hash; + return Object.keys(hash) + .map(function (id) { + return hash[id]; + }); }; - TagGLRenderer.prototype._addTag = function (tag) { - var objects = tag.glObjects; - this._tags[tag.tag.id] = [tag, []]; - for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) { - var object = objects_1[_i]; - this._tags[tag.tag.id][1].push(object); - this._scene.add(object); + TagSet.prototype.getAllDeactivated = function () { + var hashDeactivated = this._hashDeactivated; + return Object.keys(hashDeactivated) + .map(function (id) { + return hashDeactivated[id]; + }); + }; + TagSet.prototype.getDeactivated = function (id) { + return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined; + }; + TagSet.prototype.has = function (id) { + return id in this._hash; + }; + TagSet.prototype.hasDeactivated = function (id) { + return id in this._hashDeactivated; + }; + TagSet.prototype.remove = function (ids) { + this._assertActivationState(true); + var hash = this._hash; + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + if (!(id in hash)) { + continue; + } + delete hash[id]; + } + this._notifyChanged$.next(this); + }; + TagSet.prototype.removeAll = function () { + this._assertActivationState(true); + this._hash = {}; + this._notifyChanged$.next(this); + }; + TagSet.prototype.removeAllDeactivated = function () { + this._assertActivationState(false); + this._hashDeactivated = {}; + }; + TagSet.prototype.removeDeactivated = function (ids) { + this._assertActivationState(false); + var hashDeactivated = this._hashDeactivated; + for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) { + var id = ids_2[_i]; + if (!(id in hashDeactivated)) { + continue; + } + delete hashDeactivated[id]; } }; - TagGLRenderer.prototype._addCreateTag = function (tag, transform) { - var object = tag.getGLObject(transform); - this._createTag = object; - this._scene.add(object); - }; - TagGLRenderer.prototype._disposeTags = function () { - for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) { - var id = _a[_i]; - for (var _b = 0, _c = this._tags[id][1]; _b < _c.length; _b++) { - var object = _c[_b]; - this._scene.remove(object); - } - this._tags[id][0].dispose(); - delete this._tags[id]; + TagSet.prototype._add = function (tag, transform) { + if (tag instanceof Component_1.OutlineTag) { + this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform); + } + else if (tag instanceof Component_1.SpotTag) { + this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform); + } + else { + throw new Error("Tag type not supported"); } }; - TagGLRenderer.prototype._disposeCreateTag = function () { - if (this._createTag == null) { - return; + TagSet.prototype._assertActivationState = function (should) { + if (should !== this._active) { + throw new Error("Tag set not in correct state for operation."); } - var mesh = this._createTag; - this._scene.remove(mesh); - mesh.geometry.dispose(); - mesh.material.dispose(); - this._createTag = null; }; - return TagGLRenderer; -}()); -exports.TagGLRenderer = TagGLRenderer; - -},{"three":157}],253:[function(require,module,exports){ -"use strict"; -(function (TagOperation) { - TagOperation[TagOperation["None"] = 0] = "None"; - TagOperation[TagOperation["Centroid"] = 1] = "Centroid"; - TagOperation[TagOperation["Vertex"] = 2] = "Vertex"; -})(exports.TagOperation || (exports.TagOperation = {})); -var TagOperation = exports.TagOperation; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = TagOperation; - -},{}],254:[function(require,module,exports){ -"use strict"; -var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/share"); -var TagSet = (function () { - function TagSet() { - this._tagDataOperation$ = new Subject_1.Subject(); - this._set$ = new Subject_1.Subject(); - this._tagData$ = this._tagDataOperation$ - .scan(function (tagData, operation) { - return operation(tagData); - }, {}) - .share(); - this._set$ - .map(function (tags) { - return function (tagData) { - for (var _i = 0, _a = Object.keys(tagData); _i < _a.length; _i++) { - var key = _a[_i]; - delete tagData[key]; - } - for (var _b = 0, tags_1 = tags; _b < tags_1.length; _b++) { - var tag = tags_1[_b]; - tagData[tag.id] = tag; - } - return tagData; - }; - }) - .subscribe(this._tagDataOperation$); - } - Object.defineProperty(TagSet.prototype, "tagData$", { - get: function () { - return this._tagData$; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(TagSet.prototype, "set$", { - get: function () { - return this._set$; - }, - enumerable: true, - configurable: true - }); return TagSet; }()); exports.TagSet = TagSet; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = TagSet; -},{"rxjs/Subject":33,"rxjs/add/operator/map":60,"rxjs/add/operator/scan":68,"rxjs/add/operator/share":69}],255:[function(require,module,exports){ +},{"../../Component":290,"rxjs/Subject":34}],361:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Error_1 = require("../../../Error"); -var GeometryTagError = (function (_super) { +var GeometryTagError = /** @class */ (function (_super) { __extends(GeometryTagError, _super); function GeometryTagError(message) { - _super.call(this); - this.name = "GeometryTagError"; - this.message = message != null ? message : "The provided geometry value is incorrect"; + var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this; + _this.name = "GeometryTagError"; + return _this; } return GeometryTagError; }(Error_1.MapillaryError)); exports.GeometryTagError = GeometryTagError; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Error_1.MapillaryError; -},{"../../../Error":209}],256:[function(require,module,exports){ +},{"../../../Error":292}],362:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Subject_1 = require("rxjs/Subject"); /** * @class Geometry * @abstract * @classdesc Represents a geometry. */ -var Geometry = (function () { +var Geometry = /** @class */ (function () { /** * Create a geometry. * @@ -23562,6 +32265,7 @@ var Geometry = (function () { * has changed. * * @returns {Observable} Observable emitting the geometry instance. + * @ignore */ get: function () { return this._notifyChanged$; @@ -23572,22 +32276,34 @@ var Geometry = (function () { return Geometry; }()); exports.Geometry = Geometry; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Geometry; -},{"rxjs/Subject":33}],257:[function(require,module,exports){ +},{"rxjs/Subject":34}],363:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Component_1 = require("../../../Component"); /** * @class PointGeometry - * @classdesc Represents a point geometry in the basic coordinate system. + * + * @classdesc Represents a point geometry in the 2D basic image coordinate system. + * + * @example + * ``` + * var basicPoint = [0.5, 0.7]; + * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint); + * ``` */ -var PointGeometry = (function (_super) { +var PointGeometry = /** @class */ (function (_super) { __extends(PointGeometry, _super); /** * Create a point geometry. @@ -23599,13 +32315,14 @@ var PointGeometry = (function (_super) { * @throws {GeometryTagError} Point coordinates must be valid basic coordinates. */ function PointGeometry(point) { - _super.call(this); + var _this = _super.call(this) || this; var x = point[0]; var y = point[1]; if (x < 0 || x > 1 || y < 0 || y > 1) { throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1]."); } - this._point = point.slice(); + _this._point = point.slice(); + return _this; } Object.defineProperty(PointGeometry.prototype, "point", { /** @@ -23618,6 +32335,15 @@ var PointGeometry = (function (_super) { enumerable: true, configurable: true }); + /** + * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D + * basic coordinates of the point itself. + * + * @returns {Array} 2D basic coordinates representing the centroid. + */ + PointGeometry.prototype.getCentroid2d = function () { + return this._point.slice(); + }; /** * Get the 3D world coordinates for the centroid of the point, i.e. the 3D * world coordinates of the point itself. @@ -23647,19 +32373,33 @@ var PointGeometry = (function (_super) { }(Component_1.Geometry)); exports.PointGeometry = PointGeometry; -},{"../../../Component":207}],258:[function(require,module,exports){ +},{"../../../Component":290}],364:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Component_1 = require("../../../Component"); /** * @class PolygonGeometry - * @classdesc Represents a polygon geometry in the basic coordinate system. + * + * @classdesc Represents a polygon geometry in the 2D basic image coordinate system. + * All polygons and holes provided to the constructor needs to be closed. + * + * @example + * ``` + * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]]; + * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon); + * ``` */ -var PolygonGeometry = (function (_super) { +var PolygonGeometry = /** @class */ (function (_super) { __extends(PolygonGeometry, _super); /** * Create a polygon geometry. @@ -23672,7 +32412,7 @@ var PolygonGeometry = (function (_super) { * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates. */ function PolygonGeometry(polygon, holes) { - _super.call(this); + var _this = _super.call(this) || this; var polygonLength = polygon.length; if (polygonLength < 3) { throw new Component_1.GeometryTagError("A polygon must have three or more positions."); @@ -23681,18 +32421,18 @@ var PolygonGeometry = (function (_super) { polygon[0][1] !== polygon[polygonLength - 1][1]) { throw new Component_1.GeometryTagError("First and last positions must be equivalent."); } - this._polygon = []; + _this._polygon = []; for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) { var vertex = polygon_1[_i]; if (vertex[0] < 0 || vertex[0] > 1 || vertex[1] < 0 || vertex[1] > 1) { throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1]."); } - this._polygon.push(vertex.slice()); + _this._polygon.push(vertex.slice()); } - this._holes = []; + _this._holes = []; if (holes == null) { - return; + return _this; } for (var i = 0; i < holes.length; i++) { var hole = holes[i]; @@ -23704,16 +32444,17 @@ var PolygonGeometry = (function (_super) { hole[0][1] !== hole[holeLength - 1][1]) { throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent."); } - this._holes.push([]); + _this._holes.push([]); for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) { var vertex = hole_1[_a]; if (vertex[0] < 0 || vertex[0] > 1 || vertex[1] < 0 || vertex[1] > 1) { throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1]."); } - this._holes[i].push(vertex.slice()); + _this._holes[i].push(vertex.slice()); } } + return _this; } Object.defineProperty(PolygonGeometry.prototype, "polygon", { /** @@ -23750,6 +32491,18 @@ var PolygonGeometry = (function (_super) { this._polygon.splice(this._polygon.length - 1, 0, clamped); this._notifyChanged$.next(this); }; + /** + * Get the coordinates of a vertex from the polygon representation of the geometry. + * + * @description The first vertex represents the bottom-left corner with the rest of + * the vertices following in clockwise order. + * + * @param {number} index - Vertex index. + * @returns {Array} Array representing the 2D basic coordinates of the vertex. + */ + PolygonGeometry.prototype.getVertex2d = function (index) { + return this._polygon[index].slice(); + }; /** * Remove a vertex from the polygon. * @@ -23795,7 +32548,7 @@ var PolygonGeometry = (function (_super) { var maxX = Math.max.apply(Math, xs); var minY = Math.min.apply(Math, ys); var maxY = Math.max.apply(Math, ys); - var centroid = this._getCentroid2d(); + var centroid = this.getCentroid2d(); var minTranslationX = -minX; var maxTranslationX = 1 - maxX; var minTranslationY = -minY; @@ -23818,6 +32571,10 @@ var PolygonGeometry = (function (_super) { return transform.unprojectBasic(this._polygon[index], 200); }; /** @inheritdoc */ + PolygonGeometry.prototype.getVertices2d = function () { + return this._polygon.slice(); + }; + /** @inheritdoc */ PolygonGeometry.prototype.getVertices3d = function (transform) { return this._polygon .map(function (point) { @@ -23845,15 +32602,7 @@ var PolygonGeometry = (function (_super) { return holes3d; }; /** @inheritdoc */ - PolygonGeometry.prototype.getCentroid3d = function (transform) { - var centroid2d = this._getCentroid2d(); - return transform.unprojectBasic(centroid2d, 200); - }; - /** @inheritdoc */ - PolygonGeometry.prototype.getTriangles3d = function (transform) { - return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform)); - }; - PolygonGeometry.prototype._getCentroid2d = function () { + PolygonGeometry.prototype.getCentroid2d = function () { var polygon = this._polygon; var area = 0; var centroidX = 0; @@ -23873,25 +32622,55 @@ var PolygonGeometry = (function (_super) { centroidY /= 6 * area; return [centroidX, centroidY]; }; + /** @inheritdoc */ + PolygonGeometry.prototype.getCentroid3d = function (transform) { + var centroid2d = this.getCentroid2d(); + return transform.unprojectBasic(centroid2d, 200); + }; + /** @inheritdoc */ + PolygonGeometry.prototype.getTriangles3d = function (transform) { + return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform)); + }; + /** @inheritdoc */ + PolygonGeometry.prototype.getPoleOfAccessibility2d = function () { + return this._getPoleOfInaccessibility2d(this._polygon.slice()); + }; + /** @inheritdoc */ + PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) { + var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice()); + return transform.unprojectBasic(pole2d, 200); + }; return PolygonGeometry; }(Component_1.VertexGeometry)); exports.PolygonGeometry = PolygonGeometry; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = PolygonGeometry; -},{"../../../Component":207}],259:[function(require,module,exports){ +},{"../../../Component":290}],365:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Component_1 = require("../../../Component"); /** * @class RectGeometry - * @classdesc Represents a rectangle geometry in the basic coordinate system. + * + * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system. + * + * @example + * ``` + * var basicRect = [0.5, 0.3, 0.7, 0.4]; + * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect); + * ``` */ -var RectGeometry = (function (_super) { +var RectGeometry = /** @class */ (function (_super) { __extends(RectGeometry, _super); /** * Create a rectangle geometry. @@ -23903,7 +32682,7 @@ var RectGeometry = (function (_super) { * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates. */ function RectGeometry(rect) { - _super.call(this); + var _this = _super.call(this) || this; if (rect[1] > rect[3]) { throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted."); } @@ -23913,14 +32692,42 @@ var RectGeometry = (function (_super) { throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1]."); } } - this._rect = rect.slice(0, 4); - if (this._rect[0] > this._rect[2]) { - this._inverted = true; - } + _this._anchorIndex = undefined; + _this._rect = rect.slice(0, 4); + _this._inverted = _this._rect[0] > _this._rect[2]; + return _this; } + Object.defineProperty(RectGeometry.prototype, "anchorIndex", { + /** + * Get anchor index property. + * + * @returns {number} Index representing the current anchor property if + * achoring indexing has been initialized. If anchor indexing has not been + * initialized or has been terminated undefined will be returned. + */ + get: function () { + return this._anchorIndex; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RectGeometry.prototype, "inverted", { + /** + * Get inverted property. + * + * @returns {boolean} Boolean determining whether the rect geometry is + * inverted. For panoramas the rect geometrye may be inverted. + */ + get: function () { + return this._inverted; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(RectGeometry.prototype, "rect", { /** * Get rect property. + * * @returns {Array} Array representing the top-left and bottom-right * corners of the rectangle in basic coordinates. */ @@ -23930,6 +32737,225 @@ var RectGeometry = (function (_super) { enumerable: true, configurable: true }); + /** + * Initialize anchor indexing to enable setting opposite vertex. + * + * @param {number} [index] - The index of the vertex to use as anchor. + * + * @throws {Error} If anchor indexing has already been initialized. + * @throws {Error} If index is not valid (0 to 3). + */ + RectGeometry.prototype.initializeAnchorIndexing = function (index) { + if (this._anchorIndex !== undefined) { + throw new Error("Anchor indexing is already initialized."); + } + if (index < 0 || index > 3) { + throw new Error("Invalid anchor index: " + index + "."); + } + this._anchorIndex = index === undefined ? 0 : index; + }; + /** + * Terminate anchor indexing to disable setting pposite vertex. + */ + RectGeometry.prototype.terminateAnchorIndexing = function () { + this._anchorIndex = undefined; + }; + /** + * Set the value of the vertex opposite to the anchor in the polygon + * representation of the rectangle. + * + * @description Setting the opposite vertex may change the anchor index. + * + * @param {Array} opposite - The new value of the vertex opposite to the anchor. + * @param {Transform} transform - The transform of the node related to the rectangle. + * + * @throws {Error} When anchor indexing has not been initialized. + */ + RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) { + if (this._anchorIndex === undefined) { + throw new Error("Anchor indexing needs to be initialized."); + } + var changed = [ + Math.max(0, Math.min(1, opposite[0])), + Math.max(0, Math.min(1, opposite[1])), + ]; + var original = this._rect.slice(); + var anchor = this._anchorIndex === 0 ? [original[0], original[3]] : + this._anchorIndex === 1 ? [original[0], original[1]] : + this._anchorIndex === 2 ? [original[2], original[1]] : + [original[2], original[3]]; + if (transform.fullPano) { + var deltaX = this._anchorIndex < 2 ? + changed[0] - original[2] : + changed[0] - original[0]; + if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) { + // right side passes boundary rightward + this._inverted = true; + this._anchorIndex = anchor[1] > changed[1] ? 0 : 1; + } + else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) { + // left side passes right side and boundary rightward + this._inverted = true; + this._anchorIndex = anchor[1] > changed[1] ? 0 : 1; + } + else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) { + this._inverted = false; + if (anchor[0] > changed[0]) { + // left side passes boundary rightward + this._anchorIndex = anchor[1] > changed[1] ? 3 : 2; + } + else { + // left side passes right side and boundary rightward + this._anchorIndex = anchor[1] > changed[1] ? 0 : 1; + } + } + else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) { + // left side passes boundary leftward + this._inverted = true; + this._anchorIndex = anchor[1] > changed[1] ? 3 : 2; + } + else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) { + // right side passes left side and boundary leftward + this._inverted = true; + this._anchorIndex = anchor[1] > changed[1] ? 3 : 2; + } + else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) { + this._inverted = false; + if (anchor[0] > changed[0]) { + // right side passes boundary leftward + this._anchorIndex = anchor[1] > changed[1] ? 3 : 2; + } + else { + // right side passes left side and boundary leftward + this._anchorIndex = anchor[1] > changed[1] ? 0 : 1; + } + } + else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) { + // inverted and right side passes left side completing a loop + this._inverted = false; + this._anchorIndex = anchor[1] > changed[1] ? 0 : 1; + } + else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) { + // inverted and left side passes right side completing a loop + this._inverted = false; + this._anchorIndex = anchor[1] > changed[1] ? 3 : 2; + } + else if (this._inverted) { + // if still inverted only top and bottom can switch + if (this._anchorIndex < 2) { + this._anchorIndex = anchor[1] > changed[1] ? 0 : 1; + } + else { + this._anchorIndex = anchor[1] > changed[1] ? 3 : 2; + } + } + else { + // if still not inverted treat as non full pano + if (anchor[0] <= changed[0] && anchor[1] > changed[1]) { + this._anchorIndex = 0; + } + else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) { + this._anchorIndex = 1; + } + else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) { + this._anchorIndex = 2; + } + else { + this._anchorIndex = 3; + } + } + var rect = []; + if (this._anchorIndex === 0) { + rect[0] = anchor[0]; + rect[1] = changed[1]; + rect[2] = changed[0]; + rect[3] = anchor[1]; + } + else if (this._anchorIndex === 1) { + rect[0] = anchor[0]; + rect[1] = anchor[1]; + rect[2] = changed[0]; + rect[3] = changed[1]; + } + else if (this._anchorIndex === 2) { + rect[0] = changed[0]; + rect[1] = anchor[1]; + rect[2] = anchor[0]; + rect[3] = changed[1]; + } + else { + rect[0] = changed[0]; + rect[1] = changed[1]; + rect[2] = anchor[0]; + rect[3] = anchor[1]; + } + if (!this._inverted && rect[0] > rect[2] || + this._inverted && rect[0] < rect[2]) { + rect[0] = original[0]; + rect[2] = original[2]; + } + if (rect[1] > rect[3]) { + rect[1] = original[1]; + rect[3] = original[3]; + } + this._rect[0] = rect[0]; + this._rect[1] = rect[1]; + this._rect[2] = rect[2]; + this._rect[3] = rect[3]; + } + else { + if (anchor[0] <= changed[0] && anchor[1] > changed[1]) { + this._anchorIndex = 0; + } + else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) { + this._anchorIndex = 1; + } + else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) { + this._anchorIndex = 2; + } + else { + this._anchorIndex = 3; + } + var rect = []; + if (this._anchorIndex === 0) { + rect[0] = anchor[0]; + rect[1] = changed[1]; + rect[2] = changed[0]; + rect[3] = anchor[1]; + } + else if (this._anchorIndex === 1) { + rect[0] = anchor[0]; + rect[1] = anchor[1]; + rect[2] = changed[0]; + rect[3] = changed[1]; + } + else if (this._anchorIndex === 2) { + rect[0] = changed[0]; + rect[1] = anchor[1]; + rect[2] = anchor[0]; + rect[3] = changed[1]; + } + else { + rect[0] = changed[0]; + rect[1] = changed[1]; + rect[2] = anchor[0]; + rect[3] = anchor[1]; + } + if (rect[0] > rect[2]) { + rect[0] = original[0]; + rect[2] = original[2]; + } + if (rect[1] > rect[3]) { + rect[1] = original[1]; + rect[3] = original[3]; + } + this._rect[0] = rect[0]; + this._rect[1] = rect[1]; + this._rect[2] = rect[2]; + this._rect[3] = rect[3]; + } + this._notifyChanged$.next(this); + }; /** * Set the value of a vertex in the polygon representation of the rectangle. * @@ -23971,12 +32997,12 @@ var RectGeometry = (function (_super) { rect[2] = changed[0]; rect[3] = changed[1]; } - if (transform.gpano) { - var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 || + if (transform.fullPano) { + var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 || index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25; - var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 || + var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 || index >= 2 && changed[0] < 0.25 && original[2] > 0.75; - if (passingBoundaryLeft || passingBoundaryRight) { + if (passingBoundaryLeftward || passingBoundaryRightward) { this._inverted = !this._inverted; } else { @@ -24068,6 +33094,33 @@ var RectGeometry = (function (_super) { return transform.unprojectBasic(point, 200); }); }; + /** + * Get the coordinates of a vertex from the polygon representation of the geometry. + * + * @description The first vertex represents the bottom-left corner with the rest of + * the vertices following in clockwise order. The method shifts the right side + * coordinates of the rectangle by one unit to ensure that the vertices are ordered + * clockwise. + * + * @param {number} index - Vertex index. + * @returns {Array} Array representing the 2D basic coordinates of the vertex. + */ + RectGeometry.prototype.getVertex2d = function (index) { + return this._rectToVertices2d(this._rect)[index]; + }; + /** + * Get the coordinates of a vertex from the polygon representation of the geometry. + * + * @description The first vertex represents the bottom-left corner with the rest of + * the vertices following in clockwise order. The coordinates will not be shifted + * so they may not appear in clockwise order when layed out on the plane. + * + * @param {number} index - Vertex index. + * @returns {Array} Array representing the 2D basic coordinates of the vertex. + */ + RectGeometry.prototype.getNonAdjustedVertex2d = function (index) { + return this._rectToNonAdjustedVertices2d(this._rect)[index]; + }; /** * Get a vertex from the polygon representation of the 3D coordinates for the * vertices of the geometry. @@ -24083,6 +33136,18 @@ var RectGeometry = (function (_super) { RectGeometry.prototype.getVertex3d = function (index, transform) { return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200); }; + /** + * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle. + * + * @description The first vertex represents the bottom-left corner with the rest of + * the vertices following in clockwise order. + * + * @returns {Array>} Polygon array of 2D basic coordinates representing + * the rectangle vertices. + */ + RectGeometry.prototype.getVertices2d = function () { + return this._rectToVertices2d(this._rect); + }; /** * Get a polygon representation of the 3D coordinates for the vertices of the rectangle. * @@ -24100,15 +33165,29 @@ var RectGeometry = (function (_super) { }); }; /** @inheritdoc */ - RectGeometry.prototype.getCentroid3d = function (transform) { - var rect = this._rect; - var x0 = rect[0]; - var x1 = this._inverted ? rect[2] + 1 : rect[2]; - var y0 = rect[1]; - var y1 = rect[3]; - var centroidX = x0 + (x1 - x0) / 2; - var centroidY = y0 + (y1 - y0) / 2; - return transform.unprojectBasic([centroidX, centroidY], 200); + RectGeometry.prototype.getCentroid2d = function () { + var rect = this._rect; + var x0 = rect[0]; + var x1 = this._inverted ? rect[2] + 1 : rect[2]; + var y0 = rect[1]; + var y1 = rect[3]; + var centroidX = (x0 + x1) / 2; + var centroidY = (y0 + y1) / 2; + return [centroidX, centroidY]; + }; + /** @inheritdoc */ + RectGeometry.prototype.getCentroid3d = function (transform) { + var centroid2d = this.getCentroid2d(); + return transform.unprojectBasic(centroid2d, 200); + }; + /** @inheritdoc */ + RectGeometry.prototype.getPoleOfAccessibility2d = function () { + return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect)); + }; + /** @inheritdoc */ + RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) { + var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect)); + return transform.unprojectBasic(pole2d, 200); }; /** @inheritdoc */ RectGeometry.prototype.getTriangles3d = function (transform) { @@ -24164,9 +33243,12 @@ var RectGeometry = (function (_super) { }; /** * Convert the top-left, bottom-right representation of a rectangle to a polygon - * representation of the vertices starting at the bottom-right corner going + * representation of the vertices starting at the bottom-left corner going * clockwise. * + * @description The method shifts the right side coordinates of the rectangle + * by one unit to ensure that the vertices are ordered clockwise. + * * @param {Array} rect - Top-left, bottom-right representation of a * rectangle. * @returns {Array>} Polygon representation of the vertices of the @@ -24181,28 +33263,57 @@ var RectGeometry = (function (_super) { [rect[0], rect[3]], ]; }; + /** + * Convert the top-left, bottom-right representation of a rectangle to a polygon + * representation of the vertices starting at the bottom-left corner going + * clockwise. + * + * @description The first vertex represents the bottom-left corner with the rest of + * the vertices following in clockwise order. The coordinates will not be shifted + * to ensure that the vertices are ordered clockwise when layed out on the plane. + * + * @param {Array} rect - Top-left, bottom-right representation of a + * rectangle. + * @returns {Array>} Polygon representation of the vertices of the + * rectangle. + */ + RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) { + return [ + [rect[0], rect[3]], + [rect[0], rect[1]], + [rect[2], rect[1]], + [rect[2], rect[3]], + [rect[0], rect[3]], + ]; + }; return RectGeometry; }(Component_1.VertexGeometry)); exports.RectGeometry = RectGeometry; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = RectGeometry; -},{"../../../Component":207}],260:[function(require,module,exports){ -/// +},{"../../../Component":290}],366:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var earcut = require("earcut"); +var polylabel = require("@mapbox/polylabel"); var Component_1 = require("../../../Component"); /** * @class VertexGeometry * @abstract * @classdesc Represents a vertex geometry. */ -var VertexGeometry = (function (_super) { +var VertexGeometry = /** @class */ (function (_super) { __extends(VertexGeometry, _super); /** * Create a vertex geometry. @@ -24210,8 +33321,20 @@ var VertexGeometry = (function (_super) { * @constructor */ function VertexGeometry() { - _super.call(this); + return _super.call(this) || this; } + /** + * Finds the polygon pole of inaccessibility, the most distant internal + * point from the polygon outline. + * + * @param {Array>} points2d - 2d points of outline to triangulate. + * @returns {Array} Point of inaccessibility. + * @ignore + */ + VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) { + var pole2d = polylabel([points2d], 3e-2); + return pole2d; + }; /** * Triangulates a 2d polygon and returns the triangle * representation as a flattened array of 3d points. @@ -24221,6 +33344,7 @@ var VertexGeometry = (function (_super) { * @param {Array>>} [holes2d] - 2d points of holes to triangulate. * @param {Array>>} [holes3d] - 3d points of holes corresponding to the 2d points. * @returns {Array} Flattened array of 3d points ordered based on the triangles. + * @ignore */ VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) { var data = [points2d.slice(0, -1)]; @@ -24247,36 +33371,613 @@ var VertexGeometry = (function (_super) { return VertexGeometry; }(Component_1.Geometry)); exports.VertexGeometry = VertexGeometry; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = VertexGeometry; -},{"../../../Component":207,"earcut":6}],261:[function(require,module,exports){ +},{"../../../Component":290,"@mapbox/polylabel":1,"earcut":8}],367:[function(require,module,exports){ "use strict"; -(function (Alignment) { - Alignment[Alignment["Center"] = 0] = "Center"; - Alignment[Alignment["Outer"] = 1] = "Outer"; -})(exports.Alignment || (exports.Alignment = {})); -var Alignment = exports.Alignment; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Alignment; +var Subject_1 = require("rxjs/Subject"); +var Component_1 = require("../../../Component"); +var CreateHandlerBase = /** @class */ (function (_super) { + __extends(CreateHandlerBase, _super); + function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) { + var _this = _super.call(this, component, container, navigator, viewportCoords) || this; + _this._tagCreator = tagCreator; + _this._geometryCreated$ = new Subject_1.Subject(); + return _this; + } + Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", { + get: function () { + return this._geometryCreated$; + }, + enumerable: true, + configurable: true + }); + CreateHandlerBase.prototype._enable = function () { + this._enableCreate(); + this._container.element.classList.add("component-tag-create"); + }; + CreateHandlerBase.prototype._disable = function () { + this._container.element.classList.remove("component-tag-create"); + this._disableCreate(); + }; + CreateHandlerBase.prototype._validateBasic = function (basic) { + var x = basic[0]; + var y = basic[1]; + return 0 <= x && x <= 1 && 0 <= y && y <= 1; + }; + CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) { + var _this = this; + return mouseEvent$ + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .map(function (_a) { + var event = _a[0], camera = _a[1], transform = _a[2]; + return _this._mouseEventToBasic(event, _this._container.element, camera, transform); + }); + }; + return CreateHandlerBase; +}(Component_1.TagHandlerBase)); +exports.CreateHandlerBase = CreateHandlerBase; +exports.default = CreateHandlerBase; + +},{"../../../Component":290,"rxjs/Subject":34}],368:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../../Component"); +var CreatePointHandler = /** @class */ (function (_super) { + __extends(CreatePointHandler, _super); + function CreatePointHandler() { + return _super !== null && _super.apply(this, arguments) || this; + } + CreatePointHandler.prototype._enableCreate = function () { + this._container.mouseService.deferPixels(this._name, 4); + this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$) + .filter(this._validateBasic) + .map(function (basic) { + return new Component_1.PointGeometry(basic); + }) + .subscribe(this._geometryCreated$); + }; + CreatePointHandler.prototype._disableCreate = function () { + this._container.mouseService.undeferPixels(this._name); + this._geometryCreatedSubscription.unsubscribe(); + }; + CreatePointHandler.prototype._getNameExtension = function () { + return "create-point"; + }; + return CreatePointHandler; +}(Component_1.CreateHandlerBase)); +exports.CreatePointHandler = CreatePointHandler; +exports.default = CreatePointHandler; + +},{"../../../Component":290}],369:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../../Component"); +var CreatePolygonHandler = /** @class */ (function (_super) { + __extends(CreatePolygonHandler, _super); + function CreatePolygonHandler() { + return _super !== null && _super.apply(this, arguments) || this; + } + CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) { + tag.addPoint(basicPoint); + }; + Object.defineProperty(CreatePolygonHandler.prototype, "_create$", { + get: function () { + return this._tagCreator.createPolygon$; + }, + enumerable: true, + configurable: true + }); + CreatePolygonHandler.prototype._getNameExtension = function () { + return "create-polygon"; + }; + CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) { + tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform); + }; + return CreatePolygonHandler; +}(Component_1.CreateVertexHandler)); +exports.CreatePolygonHandler = CreatePolygonHandler; +exports.default = CreatePolygonHandler; + +},{"../../../Component":290}],370:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../../../Component"); +var CreateRectDragHandler = /** @class */ (function (_super) { + __extends(CreateRectDragHandler, _super); + function CreateRectDragHandler() { + return _super !== null && _super.apply(this, arguments) || this; + } + CreateRectDragHandler.prototype._enableCreate = function () { + var _this = this; + this._container.mouseService.claimMouse(this._name, 2); + this._deleteSubscription = this._navigator.stateService.currentTransform$ + .map(function (transform) { return null; }) + .skip(1) + .subscribe(this._tagCreator.delete$); + this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$)) + .filter(this._validateBasic) + .subscribe(this._tagCreator.createRect$); + this._initializeAnchorIndexingSubscription = this._tagCreator.tag$ + .filter(function (tag) { + return !!tag; + }) + .subscribe(function (tag) { + tag.geometry.initializeAnchorIndexing(); + }); + var basicMouse$ = Observable_1.Observable + .merge(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseMove$), this._container.mouseService.filtered$(this._name, this._container.mouseService.domMouseMove$)) + .combineLatest(this._container.renderService.renderCamera$) + .withLatestFrom(this._navigator.stateService.currentTransform$) + .map(function (_a) { + var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1]; + return _this._mouseEventToBasic(event, _this._container.element, camera, transform); + }); + this._setVertexSubscription = this._tagCreator.tag$ + .switchMap(function (tag) { + return !!tag ? + Observable_1.Observable + .combineLatest(Observable_1.Observable.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) : + Observable_1.Observable.empty(); + }) + .subscribe(function (_a) { + var tag = _a[0], basicPoint = _a[1], transform = _a[2]; + tag.geometry.setOppositeVertex2d(basicPoint, transform); + }); + var basicMouseDragEnd$ = this._container.mouseService.mouseDragEnd$ + .withLatestFrom(this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDrag$)) + .filter(this._validateBasic), function (event, basicPoint) { + return basicPoint; + }) + .share(); + this._addPointSubscription = this._tagCreator.tag$ + .switchMap(function (tag) { + return !!tag ? + Observable_1.Observable + .combineLatest(Observable_1.Observable.of(tag), basicMouseDragEnd$) : + Observable_1.Observable.empty(); + }) + .subscribe(function (_a) { + var tag = _a[0], basicPoint = _a[1]; + var rectGeometry = tag.geometry; + if (!rectGeometry.validate(basicPoint)) { + basicPoint = rectGeometry.getNonAdjustedVertex2d(3); + } + tag.addPoint(basicPoint); + }); + this._geometryCreatedSubscription = this._tagCreator.tag$ + .switchMap(function (tag) { + return !!tag ? + tag.created$ + .map(function (t) { + return t.geometry; + }) : + Observable_1.Observable.empty(); + }) + .subscribe(this._geometryCreated$); + }; + CreateRectDragHandler.prototype._disableCreate = function () { + this._container.mouseService.unclaimMouse(this._name); + this._tagCreator.delete$.next(null); + this._addPointSubscription.unsubscribe(); + this._createSubscription.unsubscribe(); + this._deleteSubscription.unsubscribe(); + this._geometryCreatedSubscription.unsubscribe(); + this._initializeAnchorIndexingSubscription.unsubscribe(); + this._setVertexSubscription.unsubscribe(); + }; + CreateRectDragHandler.prototype._getNameExtension = function () { + return "create-rect-drag"; + }; + return CreateRectDragHandler; +}(Component_1.CreateHandlerBase)); +exports.CreateRectDragHandler = CreateRectDragHandler; +exports.default = CreateRectDragHandler; + +},{"../../../Component":290,"rxjs/Observable":29}],371:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../../Component"); +var CreateRectHandler = /** @class */ (function (_super) { + __extends(CreateRectHandler, _super); + function CreateRectHandler() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(CreateRectHandler.prototype, "_create$", { + get: function () { + return this._tagCreator.createRect$; + }, + enumerable: true, + configurable: true + }); + CreateRectHandler.prototype._addPoint = function (tag, basicPoint) { + var rectGeometry = tag.geometry; + if (!rectGeometry.validate(basicPoint)) { + basicPoint = rectGeometry.getNonAdjustedVertex2d(3); + } + tag.addPoint(basicPoint); + }; + CreateRectHandler.prototype._enable = function () { + _super.prototype._enable.call(this); + this._initializeAnchorIndexingSubscription = this._tagCreator.tag$ + .filter(function (tag) { + return !!tag; + }) + .subscribe(function (tag) { + tag.geometry.initializeAnchorIndexing(); + }); + }; + CreateRectHandler.prototype._disable = function () { + _super.prototype._disable.call(this); + this._initializeAnchorIndexingSubscription.unsubscribe(); + }; + CreateRectHandler.prototype._getNameExtension = function () { + return "create-rect"; + }; + CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) { + tag.geometry.setOppositeVertex2d(basicPoint, transform); + }; + return CreateRectHandler; +}(Component_1.CreateVertexHandler)); +exports.CreateRectHandler = CreateRectHandler; +exports.default = CreateRectHandler; + +},{"../../../Component":290}],372:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../../../Component"); +var CreateVertexHandler = /** @class */ (function (_super) { + __extends(CreateVertexHandler, _super); + function CreateVertexHandler() { + return _super !== null && _super.apply(this, arguments) || this; + } + CreateVertexHandler.prototype._enableCreate = function () { + var _this = this; + this._container.mouseService.deferPixels(this._name, 4); + var transformChanged$ = this._navigator.stateService.currentTransform$ + .map(function (transform) { }) + .publishReplay(1) + .refCount(); + this._deleteSubscription = transformChanged$ + .skip(1) + .subscribe(this._tagCreator.delete$); + var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).share(); + this._createSubscription = transformChanged$ + .switchMap(function () { + return basicClick$ + .filter(_this._validateBasic) + .take(1); + }) + .subscribe(this._create$); + this._setVertexSubscription = this._tagCreator.tag$ + .switchMap(function (tag) { + return !!tag ? + Observable_1.Observable + .combineLatest(Observable_1.Observable.of(tag), Observable_1.Observable + .merge(_this._container.mouseService.mouseMove$, _this._container.mouseService.domMouseMove$), _this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$) : + Observable_1.Observable.empty(); + }) + .subscribe(function (_a) { + var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3]; + var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform); + _this._setVertex2d(tag, basicPoint, transform); + }); + this._addPointSubscription = this._tagCreator.tag$ + .switchMap(function (tag) { + return !!tag ? + Observable_1.Observable + .combineLatest(Observable_1.Observable.of(tag), basicClick$) : + Observable_1.Observable.empty(); + }) + .subscribe(function (_a) { + var tag = _a[0], basicPoint = _a[1]; + _this._addPoint(tag, basicPoint); + }); + this._geometryCreateSubscription = this._tagCreator.tag$ + .switchMap(function (tag) { + return !!tag ? + tag.created$ + .map(function (t) { + return t.geometry; + }) : + Observable_1.Observable.empty(); + }) + .subscribe(this._geometryCreated$); + }; + CreateVertexHandler.prototype._disableCreate = function () { + this._container.mouseService.undeferPixels(this._name); + this._tagCreator.delete$.next(null); + this._addPointSubscription.unsubscribe(); + this._createSubscription.unsubscribe(); + this._deleteSubscription.unsubscribe(); + this._geometryCreateSubscription.unsubscribe(); + this._setVertexSubscription.unsubscribe(); + }; + return CreateVertexHandler; +}(Component_1.CreateHandlerBase)); +exports.CreateVertexHandler = CreateVertexHandler; +exports.default = CreateVertexHandler; + +},{"../../../Component":290,"rxjs/Observable":29}],373:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Component_1 = require("../../../Component"); +var EditVertexHandler = /** @class */ (function (_super) { + __extends(EditVertexHandler, _super); + function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) { + var _this = _super.call(this, component, container, navigator, viewportCoords) || this; + _this._tagSet = tagSet; + return _this; + } + EditVertexHandler.prototype._enable = function () { + var _this = this; + var interaction$ = this._tagSet.changed$ + .map(function (tagSet) { + return tagSet.getAll(); + }) + .switchMap(function (tags) { + return Observable_1.Observable + .from(tags) + .mergeMap(function (tag) { + return tag.interact$; + }); + }) + .switchMap(function (interaction) { + return Observable_1.Observable + .of(interaction) + .concat(_this._container.mouseService.documentMouseUp$ + .map(function () { + return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null }; + }) + .first()); + }) + .share(); + var mouseMove$ = Observable_1.Observable + .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$) + .share(); + this._claimMouseSubscription = interaction$ + .switchMap(function (interaction) { + return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : Observable_1.Observable.empty(); + }) + .subscribe(function () { + _this._container.mouseService.claimMouse(_this._name, 3); + }); + this._cursorSubscription = interaction$ + .map(function (interaction) { + return interaction.cursor; + }) + .distinctUntilChanged() + .subscribe(function (cursor) { + var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"]; + for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) { + var interactionCursor = interactionCursors_1[_i]; + _this._container.element.classList.remove("component-tag-edit-" + interactionCursor); + } + if (!!cursor) { + _this._container.element.classList.add("component-tag-edit-" + cursor); + } + }); + this._unclaimMouseSubscription = this._container.mouseService + .filtered$(this._name, this._container.mouseService.domMouseDragEnd$) + .subscribe(function (e) { + _this._container.mouseService.unclaimMouse(_this._name); + }); + this._preventDefaultSubscription = interaction$ + .switchMap(function (interaction) { + return !!interaction.tag ? + _this._container.mouseService.documentMouseMove$ : + Observable_1.Observable.empty(); + }) + .subscribe(function (event) { + event.preventDefault(); // prevent selection of content outside the viewer + }); + this._updateGeometrySubscription = interaction$ + .withLatestFrom(mouseMove$) + .switchMap(function (_a) { + var interaction = _a[0], mouseMove = _a[1]; + if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) { + return Observable_1.Observable.empty(); + } + var mouseDrag$ = Observable_1.Observable + .of(mouseMove) + .concat(_this._container.mouseService + .filtered$(_this._name, _this._container.mouseService.domMouseDrag$) + .filter(function (event) { + return _this._viewportCoords.insideElement(event, _this._container.element); + })); + return Observable_1.Observable + .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$) + .withLatestFrom(Observable_1.Observable.of(interaction), _this._navigator.stateService.currentTransform$, function (_a, i, transform) { + var event = _a[0], render = _a[1]; + return [event, render, i, transform]; + }); + }) + .subscribe(function (_a) { + var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3]; + var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY); + var geometry = interaction.tag.geometry; + if (interaction.operation === Component_1.TagOperation.Centroid) { + geometry.setCentroid2d(basic, transform); + } + else if (interaction.operation === Component_1.TagOperation.Vertex) { + geometry.setVertex2d(interaction.vertexIndex, basic, transform); + } + }); + }; + EditVertexHandler.prototype._disable = function () { + this._claimMouseSubscription.unsubscribe(); + this._cursorSubscription.unsubscribe(); + this._preventDefaultSubscription.unsubscribe(); + this._unclaimMouseSubscription.unsubscribe(); + this._updateGeometrySubscription.unsubscribe(); + }; + EditVertexHandler.prototype._getNameExtension = function () { + return "edit-vertex"; + }; + return EditVertexHandler; +}(Component_1.TagHandlerBase)); +exports.EditVertexHandler = EditVertexHandler; +exports.default = EditVertexHandler; -},{}],262:[function(require,module,exports){ +},{"../../../Component":290,"rxjs/Observable":29}],374:[function(require,module,exports){ +"use strict"; /// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../../Component"); +var TagHandlerBase = /** @class */ (function (_super) { + __extends(TagHandlerBase, _super); + function TagHandlerBase(component, container, navigator, viewportCoords) { + var _this = _super.call(this, component, container, navigator) || this; + _this._name = _this._component.name + "-" + _this._getNameExtension(); + _this._viewportCoords = viewportCoords; + return _this; + } + TagHandlerBase.prototype._getConfiguration = function (enable) { + return {}; + }; + TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) { + offsetX = offsetX != null ? offsetX : 0; + offsetY = offsetY != null ? offsetY : 0; + var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1]; + var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective); + return basic; + }; + return TagHandlerBase; +}(Component_1.HandlerBase)); +exports.TagHandlerBase = TagHandlerBase; +exports.default = TagHandlerBase; + +},{"../../../Component":290}],375:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); var vd = require("virtual-dom"); var Subject_1 = require("rxjs/Subject"); var Component_1 = require("../../../Component"); -var OutlineCreateTag = (function () { - function OutlineCreateTag(geometry, options) { +var Geo_1 = require("../../../Geo"); +var OutlineCreateTag = /** @class */ (function () { + function OutlineCreateTag(geometry, options, transform, viewportCoords) { + var _this = this; this._geometry = geometry; this._options = { color: options.color == null ? 0xFFFFFF : options.color }; - this._created$ = new Subject_1.Subject(); + this._transform = transform; + this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords(); + this._outline = this._createOutine(); + this._glObjects = [this._outline]; this._aborted$ = new Subject_1.Subject(); + this._created$ = new Subject_1.Subject(); + this._glObjectsChanged$ = new Subject_1.Subject(); + this._geometryChangedSubscription = this._geometry.changed$ + .subscribe(function (vertexGeometry) { + _this._disposeOutline(); + _this._outline = _this._createOutine(); + _this._glObjects = [_this._outline]; + _this._glObjectsChanged$.next(_this); + }); } Object.defineProperty(OutlineCreateTag.prototype, "geometry", { get: function () { - return this._geometry; + return this._geometry; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineCreateTag.prototype, "glObjects", { + get: function () { + return this._glObjects; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineCreateTag.prototype, "aborted$", { + get: function () { + return this._aborted$; }, enumerable: true, configurable: true @@ -24288,9 +33989,9 @@ var OutlineCreateTag = (function () { enumerable: true, configurable: true }); - Object.defineProperty(OutlineCreateTag.prototype, "aborted$", { + Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", { get: function () { - return this._aborted$; + return this._glObjectsChanged$; }, enumerable: true, configurable: true @@ -24306,41 +34007,34 @@ var OutlineCreateTag = (function () { enumerable: true, configurable: true }); - OutlineCreateTag.prototype.getGLObject = function (transform) { - var polygon3d = this._geometry.getPoints3d(transform); - var positions = this._getPositions(polygon3d); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); - var material = new THREE.LineBasicMaterial({ - color: this._options.color, - linewidth: 1, - }); - return new THREE.Line(geometry, material); + OutlineCreateTag.prototype.dispose = function () { + this._disposeOutline(); + this._geometryChangedSubscription.unsubscribe(); }; - OutlineCreateTag.prototype.getDOMObjects = function (transform, matrixWorldInverse, projectionMatrix) { + OutlineCreateTag.prototype.getDOMObjects = function (camera, size) { var _this = this; var vNodes = []; + var container = { + offsetHeight: size.height, offsetWidth: size.width, + }; var abort = function (e) { e.stopPropagation(); _this._aborted$.next(_this); }; if (this._geometry instanceof Component_1.RectGeometry) { - var topLeftPoint3d = this._geometry.getVertex3d(1, transform); - var topLeftCameraSpace = this._convertToCameraSpace(topLeftPoint3d, matrixWorldInverse); - if (topLeftCameraSpace.z < 0) { - var centerCanvas = this._projectToCanvas(topLeftCameraSpace, projectionMatrix); - var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; }); + var anchorIndex = this._geometry.anchorIndex; + var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex; + var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1]; + var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera); + if (canvasPoint != null) { + var background = this._colorToBackground(this._options.color); + var transform = this._canvasToTransform(canvasPoint); var pointProperties = { - style: { - background: "#" + ("000000" + this._options.color.toString(16)).substr(-6), - left: centerCss[0], - position: "absolute", - top: centerCss[1], - }, + style: { background: background, transform: transform }, }; var completerProperties = { onclick: abort, - style: { left: centerCss[0], position: "absolute", top: centerCss[1] }, + style: { transform: transform }, }; vNodes.push(vd.h("div.TagInteractor", completerProperties, [])); vNodes.push(vd.h("div.TagVertex", pointProperties, [])); @@ -24348,11 +34042,9 @@ var OutlineCreateTag = (function () { } else if (this._geometry instanceof Component_1.PolygonGeometry) { var polygonGeometry_1 = this._geometry; - var firstVertex3d = this._geometry.getVertex3d(0, transform); - var firstCameraSpace = this._convertToCameraSpace(firstVertex3d, matrixWorldInverse); - if (firstCameraSpace.z < 0) { - var centerCanvas = this._projectToCanvas(firstCameraSpace, projectionMatrix); - var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; }); + var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1]; + var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera); + if (firstVertexCanvas != null) { var firstOnclick = polygonGeometry_1.polygon.length > 4 ? function (e) { e.stopPropagation(); @@ -24360,9 +34052,10 @@ var OutlineCreateTag = (function () { _this._created$.next(_this); } : abort; + var transform = this._canvasToTransform(firstVertexCanvas); var completerProperties = { onclick: firstOnclick, - style: { left: centerCss[0], position: "absolute", top: centerCss[1] }, + style: { transform: transform }, }; var firstClass = polygonGeometry_1.polygon.length > 4 ? "TagCompleter" : @@ -24370,36 +34063,33 @@ var OutlineCreateTag = (function () { vNodes.push(vd.h("div." + firstClass, completerProperties, [])); } if (polygonGeometry_1.polygon.length > 3) { - var lastVertex3d = this._geometry.getVertex3d(polygonGeometry_1.polygon.length - 3, transform); - var lastCameraSpace = this._convertToCameraSpace(lastVertex3d, matrixWorldInverse); - if (lastCameraSpace.z < 0) { - var centerCanvas = this._projectToCanvas(lastCameraSpace, projectionMatrix); - var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; }); + var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1]; + var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera); + if (lastVertexCanvas != null) { var remove = function (e) { e.stopPropagation(); polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3); }; + var transform = this._canvasToTransform(lastVertexCanvas); var completerProperties = { onclick: remove, - style: { left: centerCss[0], position: "absolute", top: centerCss[1] }, + style: { transform: transform }, }; vNodes.push(vd.h("div.TagInteractor", completerProperties, [])); } } - var vertices3d = this._geometry.getVertices3d(transform); - vertices3d.splice(-2, 2); - for (var _i = 0, vertices3d_1 = vertices3d; _i < vertices3d_1.length; _i++) { - var vertex = vertices3d_1[_i]; - var vertexCameraSpace = this._convertToCameraSpace(vertex, matrixWorldInverse); - if (vertexCameraSpace.z < 0) { - var centerCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix); - var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; }); + var verticesBasic = polygonGeometry_1.polygon.slice(); + verticesBasic.splice(-2, 2); + for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) { + var vertexBasic = verticesBasic_1[_i]; + var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera); + if (vertexCanvas != null) { + var background = this._colorToBackground(this._options.color); + var transform = this._canvasToTransform(vertexCanvas); var pointProperties = { style: { - background: "#" + ("000000" + this._options.color.toString(16)).substr(-6), - left: centerCss[0], - position: "absolute", - top: centerCss[1], + background: background, + transform: transform, }, }; vNodes.push(vd.h("div.TagVertex", pointProperties, [])); @@ -24421,7 +34111,37 @@ var OutlineCreateTag = (function () { polygonGeometry.addVertex2d(point); } }; - OutlineCreateTag.prototype._getPositions = function (polygon3d) { + OutlineCreateTag.prototype._canvasToTransform = function (canvas) { + var canvasX = Math.round(canvas[0]); + var canvasY = Math.round(canvas[1]); + var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)"; + return transform; + }; + OutlineCreateTag.prototype._colorToBackground = function (color) { + return "#" + ("000000" + color.toString(16)).substr(-6); + }; + OutlineCreateTag.prototype._createOutine = function () { + var polygon3d = this._geometry.getPoints3d(this._transform); + var positions = this._getLinePositions(polygon3d); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); + var material = new THREE.LineBasicMaterial({ + color: this._options.color, + linewidth: 1, + }); + return new THREE.Line(geometry, material); + }; + OutlineCreateTag.prototype._disposeOutline = function () { + if (this._outline == null) { + return; + } + var line = this._outline; + line.geometry.dispose(); + line.material.dispose(); + this._outline = null; + this._glObjects = []; + }; + OutlineCreateTag.prototype._getLinePositions = function (polygon3d) { var length = polygon3d.length; var positions = new Float32Array(length * 3); for (var i = 0; i < length; ++i) { @@ -24433,52 +34153,46 @@ var OutlineCreateTag = (function () { } return positions; }; - OutlineCreateTag.prototype._projectToCanvas = function (point, projectionMatrix) { - var projected = new THREE.Vector3(point.x, point.y, point.z) - .applyProjection(projectionMatrix); - return [(projected.x + 1) / 2, (-projected.y + 1) / 2]; - }; - OutlineCreateTag.prototype._convertToCameraSpace = function (point, matrixWorldInverse) { - return new THREE.Vector3(point[0], point[1], point[2]).applyMatrix4(matrixWorldInverse); - }; return OutlineCreateTag; }()); exports.OutlineCreateTag = OutlineCreateTag; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = OutlineCreateTag; -},{"../../../Component":207,"rxjs/Subject":33,"three":157,"virtual-dom":163}],263:[function(require,module,exports){ -/// +},{"../../../Component":290,"../../../Geo":293,"rxjs/Subject":34,"three":240,"virtual-dom":246}],376:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); var vd = require("virtual-dom"); var Component_1 = require("../../../Component"); -var Viewer_1 = require("../../../Viewer"); /** * @class OutlineRenderTag * @classdesc Tag visualizing the properties of an OutlineTag. */ -var OutlineRenderTag = (function (_super) { +var OutlineRenderTag = /** @class */ (function (_super) { __extends(OutlineRenderTag, _super); function OutlineRenderTag(tag, transform) { - var _this = this; - _super.call(this, tag, transform); - this._fill = this._tag.fillOpacity > 0 && !transform.gpano ? - this._createFill() : + var _this = _super.call(this, tag, transform) || this; + _this._fill = !transform.gpano ? + _this._createFill() : null; - this._holes = this._tag.lineWidth >= 1 ? - this._createHoles() : + _this._holes = _this._tag.lineWidth >= 1 ? + _this._createHoles() : []; - this._outline = this._tag.lineWidth >= 1 ? - this._createOutline() : + _this._outline = _this._tag.lineWidth >= 1 ? + _this._createOutline() : null; - this._glObjects = this._createGLObjects(); - this._tag.geometry.changed$ + _this._geometryChangedSubscription = _this._tag.geometry.changed$ .subscribe(function (geometry) { if (_this._fill != null) { _this._updateFillGeometry(); @@ -24490,20 +34204,14 @@ var OutlineRenderTag = (function (_super) { _this._updateOulineGeometry(); } }); - this._tag.changed$ + _this._changedSubscription = _this._tag.changed$ .subscribe(function (changedTag) { var glObjectsChanged = false; - if (_this._fill == null) { - if (_this._tag.fillOpacity > 0 && !_this._transform.gpano) { - _this._fill = _this._createFill(); - glObjectsChanged = true; - } - } - else { - _this._updateFillMaterial(); + if (_this._fill != null) { + _this._updateFillMaterial(_this._fill.material); } if (_this._outline == null) { - if (_this._tag.lineWidth > 0) { + if (_this._tag.lineWidth >= 1) { _this._holes = _this._createHoles(); _this._outline = _this._createOutline(); glObjectsChanged = true; @@ -24514,150 +34222,132 @@ var OutlineRenderTag = (function (_super) { _this._updateOutlineMaterial(); } if (glObjectsChanged) { - _this._glObjects = _this._createGLObjects(); _this._glObjectsChanged$.next(_this); } }); + return _this; } OutlineRenderTag.prototype.dispose = function () { this._disposeFill(); this._disposeHoles(); this._disposeOutline(); + this._changedSubscription.unsubscribe(); + this._geometryChangedSubscription.unsubscribe(); }; - OutlineRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) { + OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) { var _this = this; var vNodes = []; - if (this._tag.geometry instanceof Component_1.RectGeometry) { - if (this._tag.icon != null) { - var iconVertex = this._tag.geometry.getVertex3d(this._tag.iconIndex, this._transform); - var iconCameraSpace = this._convertToCameraSpace(iconVertex, matrixWorldInverse); - if (iconCameraSpace.z < 0) { - var interact = function (e) { - _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag }); - }; - if (atlas.loaded) { - var spriteAlignments = this._getSpriteAlignment(this._tag.iconIndex, this._tag.iconAlignment); - var sprite = atlas.getDOMSprite(this._tag.icon, spriteAlignments[0], spriteAlignments[1]); - var click = function (e) { - e.stopPropagation(); - _this._tag.click$.next(_this._tag); - }; - var iconCanvas = this._projectToCanvas(iconCameraSpace, projectionMatrix); - var iconCss = iconCanvas.map(function (coord) { return (100 * coord) + "%"; }); - var properties = { - onclick: click, - onmousedown: interact, - style: { - left: iconCss[0], - pointerEvents: "all", - position: "absolute", - top: iconCss[1], - }, - }; - vNodes.push(vd.h("div.TagSymbol", properties, [sprite])); - } - } - } - else if (this._tag.text != null) { - var textVertex = this._tag.geometry.getVertex3d(3, this._transform); - var textCameraSpace = this._convertToCameraSpace(textVertex, matrixWorldInverse); - if (textCameraSpace.z < 0) { - var interact = function (e) { - _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag }); + var isRect = this._tag.geometry instanceof Component_1.RectGeometry; + var isPerspective = !this._transform.gpano; + var container = { + offsetHeight: size.height, offsetWidth: size.width, + }; + if (this._tag.icon != null && (isRect || isPerspective)) { + var _a = this._tag.geometry instanceof Component_1.RectGeometry ? + this._tag.geometry.getVertex2d(this._tag.iconIndex) : + this._tag.geometry.getPoleOfAccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1]; + var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera); + if (iconCanvas != null) { + var interact = function (e) { + _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag }); + }; + if (atlas.loaded) { + var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat); + var iconCanvasX = Math.round(iconCanvas[0]); + var iconCanvasY = Math.round(iconCanvas[1]); + var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)"; + var click = function (e) { + e.stopPropagation(); + _this._tag.click$.next(_this._tag); }; - var labelCanvas = this._projectToCanvas(textCameraSpace, projectionMatrix); - var labelCss = labelCanvas.map(function (coord) { return (100 * coord) + "%"; }); var properties = { + onclick: click, onmousedown: interact, - style: { - color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6), - left: labelCss[0], - pointerEvents: "all", - position: "absolute", - top: labelCss[1], - }, - textContent: this._tag.text, + style: { transform: transform }, }; - vNodes.push(vd.h("span.TagSymbol", properties, [])); + vNodes.push(vd.h("div.TagSymbol", properties, [sprite])); } } } + else if (this._tag.text != null && (isRect || isPerspective)) { + var _b = this._tag.geometry instanceof Component_1.RectGeometry ? + this._tag.geometry.getVertex2d(3) : + this._tag.geometry.getPoleOfAccessibility2d(), textBasicX = _b[0], textBasicY = _b[1]; + var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera); + if (textCanvas != null) { + var textCanvasX = Math.round(textCanvas[0]); + var textCanvasY = Math.round(textCanvas[1]); + var transform = this._tag.geometry instanceof Component_1.RectGeometry ? + "translate(" + textCanvasX + "px," + textCanvasY + "px)" : + "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)"; + var interact = function (e) { + _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag }); + }; + var properties = { + onmousedown: interact, + style: { + color: this._colorToCss(this._tag.textColor), + transform: transform, + }, + textContent: this._tag.text, + }; + vNodes.push(vd.h("span.TagSymbol", properties, [])); + } + } if (!this._tag.editable) { return vNodes; } - var lineColor = "#" + ("000000" + this._tag.lineColor.toString(16)).substr(-6); + var lineColor = this._colorToCss(this._tag.lineColor); if (this._tag.geometry instanceof Component_1.RectGeometry) { - var centroid3d = this._tag.geometry.getCentroid3d(this._transform); - var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse); - if (centroidCameraSpace.z < 0) { - var interact = this._interact(Component_1.TagOperation.Centroid); - var centerCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix); - var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; }); + var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1]; + var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera); + if (centroidCanvas != null) { + var interact = this._interact(Component_1.TagOperation.Centroid, "move"); + var centroidCanvasX = Math.round(centroidCanvas[0]); + var centroidCanvasY = Math.round(centroidCanvas[1]); + var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)"; var properties = { onmousedown: interact, - style: { background: lineColor, left: centerCss[0], position: "absolute", top: centerCss[1] }, + style: { background: lineColor, transform: transform }, }; vNodes.push(vd.h("div.TagMover", properties, [])); } } - var vertices3d = this._tag.geometry.getVertices3d(this._transform); - for (var i = 0; i < vertices3d.length - 1; i++) { - var isRectGeometry = this._tag.geometry instanceof Component_1.RectGeometry; - if (isRectGeometry && + var vertices2d = this._tag.geometry.getVertices2d(); + for (var i = 0; i < vertices2d.length - 1; i++) { + if (isRect && ((this._tag.icon != null && i === this._tag.iconIndex) || (this._tag.icon == null && this._tag.text != null && i === 3))) { continue; } - var vertexCameraSpace = this._convertToCameraSpace(vertices3d[i], matrixWorldInverse); - if (vertexCameraSpace.z > 0) { + var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1]; + var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera); + if (vertexCanvas == null) { continue; } - var interact = this._interact(Component_1.TagOperation.Vertex, i); - var vertexCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix); - var vertexCss = vertexCanvas.map(function (coord) { return (100 * coord) + "%"; }); + var cursor = isRect ? + i % 2 === 0 ? "nesw-resize" : "nwse-resize" : + "crosshair"; + var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i); + var vertexCanvasX = Math.round(vertexCanvas[0]); + var vertexCanvasY = Math.round(vertexCanvas[1]); + var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)"; var properties = { onmousedown: interact, - style: { - background: lineColor, - left: vertexCss[0], - position: "absolute", - top: vertexCss[1], - }, + style: { background: lineColor, transform: transform, cursor: cursor }, }; - if (isRectGeometry) { - properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize"; - } vNodes.push(vd.h("div.TagResizer", properties, [])); if (!this._tag.indicateVertices) { continue; } var pointProperties = { - style: { - background: lineColor, - left: vertexCss[0], - position: "absolute", - top: vertexCss[1], - }, + style: { background: lineColor, transform: transform }, }; vNodes.push(vd.h("div.TagVertex", pointProperties, [])); } return vNodes; }; - OutlineRenderTag.prototype._createFill = function () { - var triangles = this._tag.geometry.getTriangles3d(this._transform); - var positions = new Float32Array(triangles); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); - geometry.computeBoundingSphere(); - var material = new THREE.MeshBasicMaterial({ - color: this._tag.fillColor, - opacity: this._tag.fillOpacity, - side: THREE.DoubleSide, - transparent: true, - }); - return new THREE.Mesh(geometry, material); - }; - OutlineRenderTag.prototype._createGLObjects = function () { + OutlineRenderTag.prototype.getGLObjects = function () { var glObjects = []; if (this._fill != null) { glObjects.push(this._fill); @@ -24671,6 +34361,22 @@ var OutlineRenderTag = (function (_super) { } return glObjects; }; + OutlineRenderTag.prototype.getRetrievableObjects = function () { + return this._fill != null ? [this._fill] : []; + }; + OutlineRenderTag.prototype._colorToCss = function (color) { + return "#" + ("000000" + color.toString(16)).substr(-6); + }; + OutlineRenderTag.prototype._createFill = function () { + var triangles = this._tag.geometry.getTriangles3d(this._transform); + var positions = new Float32Array(triangles); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true }); + this._updateFillMaterial(material); + return new THREE.Mesh(geometry, material); + }; OutlineRenderTag.prototype._createHoles = function () { var holes = []; if (this._tag.geometry instanceof Component_1.PolygonGeometry) { @@ -24689,11 +34395,11 @@ var OutlineRenderTag = (function (_super) { var geometry = new THREE.BufferGeometry(); geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); geometry.computeBoundingSphere(); - var material = new THREE.LineBasicMaterial({ - color: this._tag.lineColor, - linewidth: this._tag.lineWidth, - }); - return new THREE.Line(geometry, material); + var material = new THREE.LineBasicMaterial(); + this._updateLineBasicMaterial(material); + var line = new THREE.Line(geometry, material); + line.renderOrder = 1; + return line; }; OutlineRenderTag.prototype._createOutline = function () { var points3d = this._tag.geometry.getPoints3d(this._transform); @@ -24735,39 +34441,13 @@ var OutlineRenderTag = (function (_super) { } return positions; }; - OutlineRenderTag.prototype._getSpriteAlignment = function (index, alignment) { - var horizontalAlignment = Viewer_1.SpriteAlignment.Center; - var verticalAlignment = Viewer_1.SpriteAlignment.Center; - if (alignment === Component_1.Alignment.Outer) { - switch (index) { - case 0: - horizontalAlignment = Viewer_1.SpriteAlignment.End; - verticalAlignment = Viewer_1.SpriteAlignment.Start; - break; - case 1: - horizontalAlignment = Viewer_1.SpriteAlignment.End; - verticalAlignment = Viewer_1.SpriteAlignment.End; - break; - case 2: - horizontalAlignment = Viewer_1.SpriteAlignment.Start; - verticalAlignment = Viewer_1.SpriteAlignment.End; - break; - case 3: - horizontalAlignment = Viewer_1.SpriteAlignment.Start; - verticalAlignment = Viewer_1.SpriteAlignment.Start; - break; - default: - break; - } - } - return [horizontalAlignment, verticalAlignment]; - }; - OutlineRenderTag.prototype._interact = function (operation, vertexIndex) { + OutlineRenderTag.prototype._interact = function (operation, cursor, vertexIndex) { var _this = this; return function (e) { var offsetX = e.offsetX - e.target.offsetWidth / 2; var offsetY = e.offsetY - e.target.offsetHeight / 2; _this._interact$.next({ + cursor: cursor, offsetX: offsetX, offsetY: offsetY, operation: operation, @@ -24791,8 +34471,7 @@ var OutlineRenderTag = (function (_super) { } geometry.computeBoundingSphere(); }; - OutlineRenderTag.prototype._updateFillMaterial = function () { - var material = this._fill.material; + OutlineRenderTag.prototype._updateFillMaterial = function (material) { material.color = new THREE.Color(this._tag.fillColor); material.opacity = this._tag.fillOpacity; material.needsUpdate = true; @@ -24835,272 +34514,664 @@ var OutlineRenderTag = (function (_super) { OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) { material.color = new THREE.Color(this._tag.lineColor); material.linewidth = Math.max(this._tag.lineWidth, 1); - material.opacity = this._tag.lineWidth >= 1 ? 1 : 0; - material.transparent = this._tag.lineWidth <= 0; + material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0; + material.opacity = this._tag.lineOpacity; + material.transparent = this._tag.lineOpacity < 1; material.needsUpdate = true; }; return OutlineRenderTag; }(Component_1.RenderTag)); exports.OutlineRenderTag = OutlineRenderTag; -},{"../../../Component":207,"../../../Viewer":216,"three":157,"virtual-dom":163}],264:[function(require,module,exports){ +},{"../../../Component":290,"three":240,"virtual-dom":246}],377:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Subject_1 = require("rxjs/Subject"); var Component_1 = require("../../../Component"); +var Viewer_1 = require("../../../Viewer"); /** * @class OutlineTag + * * @classdesc Tag holding properties for visualizing a geometry outline. + * + * @example + * ``` + * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]); + * var tag = new Mapillary.TagComponent.OutlineTag( + * "id-1", + * geometry + * { editable: true, lineColor: 0xff0000 }); + * + * tagComponent.add([tag]); + * ``` */ -var OutlineTag = (function (_super) { +var OutlineTag = /** @class */ (function (_super) { __extends(OutlineTag, _super); /** * Create an outline tag. * * @override * @constructor - * @param {string} id - * @param {Geometry} geometry + * @param {string} id - Unique identifier of the tag. + * @param {VertexGeometry} geometry - Geometry defining vertices of tag. * @param {IOutlineTagOptions} options - Options defining the visual appearance and * behavior of the outline tag. */ function OutlineTag(id, geometry, options) { - var _this = this; - _super.call(this, id, geometry); - this._editable = options.editable == null ? false : options.editable; - this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor; - this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity; - this._icon = options.icon === undefined ? null : options.icon; - this._iconAlignment = options.iconAlignment == null ? Component_1.Alignment.Outer : options.iconAlignment; - this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex; - this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices; - this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor; - this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth; - this._text = options.text === undefined ? null : options.text; - this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor; - this._click$ = new Subject_1.Subject(); - this._click$ + var _this = _super.call(this, id, geometry) || this; + options = !!options ? options : {}; + _this._editable = options.editable == null ? false : options.editable; + _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor; + _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity; + _this._icon = options.icon === undefined ? null : options.icon; + _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat; + _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex; + _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices; + _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor; + _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity; + _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth; + _this._text = options.text === undefined ? null : options.text; + _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor; + _this._click$ = new Subject_1.Subject(); + _this._click$ .subscribe(function (t) { _this.fire(OutlineTag.click, _this); }); + return _this; } Object.defineProperty(OutlineTag.prototype, "click$", { /** - * Click observable. - * - * @description An observable emitting the tag when the icon of the - * tag has been clicked. - * - * @returns {Observable} + * Click observable. + * + * @description An observable emitting the tag when the icon of the + * tag has been clicked. + * + * @returns {Observable} + */ + get: function () { + return this._click$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineTag.prototype, "editable", { + /** + * Get editable property. + * @returns {boolean} Value indicating if tag is editable. + */ + get: function () { + return this._editable; + }, + /** + * Set editable property. + * @param {boolean} + * + * @fires Tag#changed + */ + set: function (value) { + this._editable = value; + this._notifyChanged$.next(this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineTag.prototype, "fillColor", { + /** + * Get fill color property. + * @returns {number} + */ + get: function () { + return this._fillColor; + }, + /** + * Set fill color property. + * @param {number} + * + * @fires Tag#changed + */ + set: function (value) { + this._fillColor = value; + this._notifyChanged$.next(this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineTag.prototype, "fillOpacity", { + /** + * Get fill opacity property. + * @returns {number} + */ + get: function () { + return this._fillOpacity; + }, + /** + * Set fill opacity property. + * @param {number} + * + * @fires Tag#changed + */ + set: function (value) { + this._fillOpacity = value; + this._notifyChanged$.next(this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineTag.prototype, "geometry", { + /** @inheritdoc */ + get: function () { + return this._geometry; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineTag.prototype, "icon", { + /** + * Get icon property. + * @returns {string} + */ + get: function () { + return this._icon; + }, + /** + * Set icon property. + * @param {string} + * + * @fires Tag#changed + */ + set: function (value) { + this._icon = value; + this._notifyChanged$.next(this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineTag.prototype, "iconFloat", { + /** + * Get icon float property. + * @returns {Alignment} + */ + get: function () { + return this._iconFloat; + }, + /** + * Set icon float property. + * @param {Alignment} + * + * @fires Tag#changed + */ + set: function (value) { + this._iconFloat = value; + this._notifyChanged$.next(this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OutlineTag.prototype, "iconIndex", { + /** + * Get icon index property. + * @returns {number} */ get: function () { - return this._click$; + return this._iconIndex; + }, + /** + * Set icon index property. + * @param {number} + * + * @fires Tag#changed + */ + set: function (value) { + this._iconIndex = value; + this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "editable", { + Object.defineProperty(OutlineTag.prototype, "indicateVertices", { /** - * Get editable property. - * @returns {boolean} Value indicating if tag is editable. + * Get indicate vertices property. + * @returns {boolean} Value indicating if vertices should be indicated + * when tag is editable. */ get: function () { - return this._editable; + return this._indicateVertices; }, /** - * Set editable property. + * Set indicate vertices property. * @param {boolean} * * @fires Tag#changed */ set: function (value) { - this._editable = value; + this._indicateVertices = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "fillColor", { + Object.defineProperty(OutlineTag.prototype, "lineColor", { /** - * Get fill color property. + * Get line color property. * @returns {number} */ get: function () { - return this._fillColor; + return this._lineColor; }, /** - * Set fill color property. + * Set line color property. * @param {number} * * @fires Tag#changed */ set: function (value) { - this._fillColor = value; + this._lineColor = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "fillOpacity", { + Object.defineProperty(OutlineTag.prototype, "lineOpacity", { /** - * Get fill opacity property. + * Get line opacity property. * @returns {number} */ get: function () { - return this._fillOpacity; + return this._lineOpacity; }, /** - * Set fill opacity property. + * Set line opacity property. * @param {number} * * @fires Tag#changed */ set: function (value) { - this._fillOpacity = value; + this._lineOpacity = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "geometry", { + Object.defineProperty(OutlineTag.prototype, "lineWidth", { + /** + * Get line width property. + * @returns {number} + */ get: function () { - return this._geometry; + return this._lineWidth; + }, + /** + * Set line width property. + * @param {number} + * + * @fires Tag#changed + */ + set: function (value) { + this._lineWidth = value; + this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "icon", { + Object.defineProperty(OutlineTag.prototype, "text", { /** - * Get icon property. + * Get text property. * @returns {string} */ get: function () { - return this._icon; + return this._text; }, /** - * Set icon property. + * Set text property. * @param {string} * * @fires Tag#changed */ set: function (value) { - this._icon = value; + this._text = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "iconAlignment", { + Object.defineProperty(OutlineTag.prototype, "textColor", { /** - * Get icon alignment property. - * @returns {Alignment} + * Get text color property. + * @returns {number} */ get: function () { - return this._iconAlignment; + return this._textColor; }, /** - * Set icon alignment property. - * @param {Alignment} + * Set text color property. + * @param {number} * * @fires Tag#changed */ set: function (value) { - this._iconAlignment = value; + this._textColor = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "iconIndex", { + /** + * Set options for tag. + * + * @description Sets all the option properties provided and keeps + * the rest of the values as is. + * + * @param {IOutlineTagOptions} options - Outline tag options + * + * @fires {Tag#changed} + */ + OutlineTag.prototype.setOptions = function (options) { + this._editable = options.editable == null ? this._editable : options.editable; + this._icon = options.icon === undefined ? this._icon : options.icon; + this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat; + this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex; + this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices; + this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor; + this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth; + this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor; + this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity; + this._text = options.text === undefined ? this._text : options.text; + this._textColor = options.textColor == null ? this._textColor : options.textColor; + this._notifyChanged$.next(this); + }; + /** + * Event fired when the icon of the outline tag is clicked. + * + * @event OutlineTag#click + * @type {OutlineTag} The tag instance that was clicked. + */ + OutlineTag.click = "click"; + return OutlineTag; +}(Component_1.Tag)); +exports.OutlineTag = OutlineTag; +exports.default = OutlineTag; + +},{"../../../Component":290,"../../../Viewer":301,"rxjs/Subject":34}],378:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var Subject_1 = require("rxjs/Subject"); +var Geo_1 = require("../../../Geo"); +var RenderTag = /** @class */ (function () { + function RenderTag(tag, transform, viewportCoords) { + this._tag = tag; + this._transform = transform; + this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords(); + this._glObjectsChanged$ = new Subject_1.Subject(); + this._interact$ = new Subject_1.Subject(); + } + Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", { + get: function () { + return this._glObjectsChanged$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RenderTag.prototype, "interact$", { + get: function () { + return this._interact$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RenderTag.prototype, "tag", { + get: function () { + return this._tag; + }, + enumerable: true, + configurable: true + }); + return RenderTag; +}()); +exports.RenderTag = RenderTag; +exports.default = RenderTag; + +},{"../../../Geo":293,"rxjs/Subject":34}],379:[function(require,module,exports){ +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Component_1 = require("../../../Component"); +var Viewer_1 = require("../../../Viewer"); +/** + * @class SpotRenderTag + * @classdesc Tag visualizing the properties of a SpotTag. + */ +var SpotRenderTag = /** @class */ (function (_super) { + __extends(SpotRenderTag, _super); + function SpotRenderTag() { + return _super !== null && _super.apply(this, arguments) || this; + } + SpotRenderTag.prototype.dispose = function () { }; + SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) { + var _this = this; + var tag = this._tag; + var container = { + offsetHeight: size.height, offsetWidth: size.width, + }; + var vNodes = []; + var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1]; + var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera); + if (centroidCanvas != null) { + var interactNone = function (e) { + _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag }); + }; + var canvasX = Math.round(centroidCanvas[0]); + var canvasY = Math.round(centroidCanvas[1]); + if (tag.icon != null) { + if (atlas.loaded) { + var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom); + var iconTransform = "translate(" + canvasX + "px," + (canvasY + 8) + "px)"; + var properties = { + onmousedown: interactNone, + style: { + pointerEvents: "all", + transform: iconTransform, + }, + }; + vNodes.push(vd.h("div", properties, [sprite])); + } + } + else if (tag.text != null) { + var textTransform = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)"; + var properties = { + onmousedown: interactNone, + style: { + color: this._colorToCss(tag.textColor), + transform: textTransform, + }, + textContent: tag.text, + }; + vNodes.push(vd.h("span.TagSymbol", properties, [])); + } + var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move"); + var background = this._colorToCss(tag.color); + var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)"; + if (tag.editable) { + var interactorProperties = { + onmousedown: interact, + style: { + background: background, + transform: transform, + }, + }; + vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, [])); + } + var pointProperties = { + style: { + background: background, + transform: transform, + }, + }; + vNodes.push(vd.h("div.TagVertex", pointProperties, [])); + } + return vNodes; + }; + SpotRenderTag.prototype.getGLObjects = function () { return []; }; + SpotRenderTag.prototype.getRetrievableObjects = function () { return []; }; + SpotRenderTag.prototype._colorToCss = function (color) { + return "#" + ("000000" + color.toString(16)).substr(-6); + }; + SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) { + var _this = this; + return function (e) { + var offsetX = e.offsetX - e.target.offsetWidth / 2; + var offsetY = e.offsetY - e.target.offsetHeight / 2; + _this._interact$.next({ + cursor: cursor, + offsetX: offsetX, + offsetY: offsetY, + operation: operation, + tag: tag, + vertexIndex: vertexIndex, + }); + }; + }; + return SpotRenderTag; +}(Component_1.RenderTag)); +exports.SpotRenderTag = SpotRenderTag; + +},{"../../../Component":290,"../../../Viewer":301,"virtual-dom":246}],380:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Component_1 = require("../../../Component"); +/** + * @class SpotTag + * + * @classdesc Tag holding properties for visualizing the centroid of a geometry. + * + * @example + * ``` + * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]); + * var tag = new Mapillary.TagComponent.SpotTag( + * "id-1", + * geometry + * { editable: true, color: 0xff0000 }); + * + * tagComponent.add([tag]); + * ``` + */ +var SpotTag = /** @class */ (function (_super) { + __extends(SpotTag, _super); + /** + * Create a spot tag. + * + * @override + * @constructor + * @param {string} id + * @param {Geometry} geometry + * @param {IOutlineTagOptions} options - Options defining the visual appearance and + * behavior of the spot tag. + */ + function SpotTag(id, geometry, options) { + var _this = _super.call(this, id, geometry) || this; + options = !!options ? options : {}; + _this._color = options.color == null ? 0xFFFFFF : options.color; + _this._editable = options.editable == null ? false : options.editable; + _this._icon = options.icon === undefined ? null : options.icon; + _this._text = options.text === undefined ? null : options.text; + _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor; + return _this; + } + Object.defineProperty(SpotTag.prototype, "color", { /** - * Get icon index property. - * @returns {number} + * Get color property. + * @returns {number} The color of the spot as a hexagonal number; */ get: function () { - return this._iconIndex; + return this._color; }, /** - * Set icon index property. + * Set color property. * @param {number} * * @fires Tag#changed */ set: function (value) { - this._iconIndex = value; + this._color = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "indicateVertices", { + Object.defineProperty(SpotTag.prototype, "editable", { /** - * Get indicate vertices property. - * @returns {boolean} Value indicating if vertices should be indicated - * when tag is editable. + * Get editable property. + * @returns {boolean} Value indicating if tag is editable. */ get: function () { - return this._indicateVertices; + return this._editable; }, /** - * Set indicate vertices property. + * Set editable property. * @param {boolean} * * @fires Tag#changed */ set: function (value) { - this._indicateVertices = value; - this._notifyChanged$.next(this); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(OutlineTag.prototype, "lineColor", { - /** - * Get line color property. - * @returns {number} - */ - get: function () { - return this._lineColor; - }, - /** - * Set line color property. - * @param {number} - * - * @fires Tag#changed - */ - set: function (value) { - this._lineColor = value; + this._editable = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "lineWidth", { + Object.defineProperty(SpotTag.prototype, "icon", { /** - * Get line width property. - * @returns {number} + * Get icon property. + * @returns {string} */ get: function () { - return this._lineWidth; + return this._icon; }, /** - * Set line width property. - * @param {number} + * Set icon property. + * @param {string} * * @fires Tag#changed */ set: function (value) { - this._lineWidth = value; + this._icon = value; this._notifyChanged$.next(this); }, enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "text", { + Object.defineProperty(SpotTag.prototype, "text", { /** * Get text property. * @returns {string} @@ -25121,7 +35192,7 @@ var OutlineTag = (function (_super) { enumerable: true, configurable: true }); - Object.defineProperty(OutlineTag.prototype, "textColor", { + Object.defineProperty(SpotTag.prototype, "textColor", { /** * Get text color property. * @returns {number} @@ -25148,631 +35219,826 @@ var OutlineTag = (function (_super) { * @description Sets all the option properties provided and keps * the rest of the values as is. * - * @param {IOutlineTagOptions} options - Outline tag options + * @param {ISpotTagOptions} options - Spot tag options * * @fires {Tag#changed} */ - OutlineTag.prototype.setOptions = function (options) { + SpotTag.prototype.setOptions = function (options) { + this._color = options.color == null ? this._color : options.color; this._editable = options.editable == null ? this._editable : options.editable; this._icon = options.icon === undefined ? this._icon : options.icon; - this._iconAlignment = options.iconAlignment == null ? this._iconAlignment : options.iconAlignment; - this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex; - this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices; - this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor; - this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth; - this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor; - this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity; this._text = options.text === undefined ? this._text : options.text; this._textColor = options.textColor == null ? this._textColor : options.textColor; this._notifyChanged$.next(this); }; - /** - * Event fired when the icon of the outline tag is clicked. - * - * @event OutlineTag#click - * @type {OutlineTag} The tag instance that was clicked. - */ - OutlineTag.click = "click"; - return OutlineTag; + return SpotTag; }(Component_1.Tag)); -exports.OutlineTag = OutlineTag; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = OutlineTag; +exports.SpotTag = SpotTag; +exports.default = SpotTag; -},{"../../../Component":207,"rxjs/Subject":33}],265:[function(require,module,exports){ -/// +},{"../../../Component":290}],381:[function(require,module,exports){ "use strict"; -var THREE = require("three"); +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var Subject_1 = require("rxjs/Subject"); -var RenderTag = (function () { - function RenderTag(tag, transform) { - this._tag = tag; - this._transform = transform; - this._glObjects = []; - this._glObjectsChanged$ = new Subject_1.Subject(); - this._interact$ = new Subject_1.Subject(); +var Utils_1 = require("../../../Utils"); +/** + * @class Tag + * @abstract + * @classdesc Abstract class representing the basic functionality of for a tag. + */ +var Tag = /** @class */ (function (_super) { + __extends(Tag, _super); + /** + * Create a tag. + * + * @constructor + * @param {string} id + * @param {Geometry} geometry + */ + function Tag(id, geometry) { + var _this = _super.call(this) || this; + _this._id = id; + _this._geometry = geometry; + _this._notifyChanged$ = new Subject_1.Subject(); + _this._notifyChanged$ + .subscribe(function (t) { + _this.fire(Tag.changed, _this); + }); + _this._geometry.changed$ + .subscribe(function (g) { + _this.fire(Tag.geometrychanged, _this); + }); + return _this; } - Object.defineProperty(RenderTag.prototype, "glObjects", { + Object.defineProperty(Tag.prototype, "id", { /** - * Get the GL objects for rendering of the tag. - * @return {Array} + * Get id property. + * @returns {string} */ get: function () { - return this._glObjects; + return this._id; }, enumerable: true, configurable: true }); - Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", { + Object.defineProperty(Tag.prototype, "geometry", { + /** + * Get geometry property. + * @returns {Geometry} The geometry of the tag. + */ get: function () { - return this._glObjectsChanged$; + return this._geometry; }, enumerable: true, configurable: true }); - Object.defineProperty(RenderTag.prototype, "interact$", { + Object.defineProperty(Tag.prototype, "changed$", { + /** + * Get changed observable. + * @returns {Observable} + * @ignore + */ get: function () { - return this._interact$; + return this._notifyChanged$; }, enumerable: true, configurable: true }); - Object.defineProperty(RenderTag.prototype, "tag", { + Object.defineProperty(Tag.prototype, "geometryChanged$", { + /** + * Get geometry changed observable. + * @returns {Observable} + * @ignore + */ get: function () { - return this._tag; + var _this = this; + return this._geometry.changed$ + .map(function (geometry) { + return _this; + }) + .share(); + }, + enumerable: true, + configurable: true + }); + /** + * Event fired when a property related to the visual appearance of the + * tag has changed. + * + * @event Tag#changed + * @type {Tag} The tag instance that has changed. + */ + Tag.changed = "changed"; + /** + * Event fired when the geometry of the tag has changed. + * + * @event Tag#geometrychanged + * @type {Tag} The tag instance whose geometry has changed. + */ + Tag.geometrychanged = "geometrychanged"; + return Tag; +}(Utils_1.EventEmitter)); +exports.Tag = Tag; +exports.default = Tag; + +},{"../../../Utils":300,"rxjs/Subject":34}],382:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var HandlerBase = /** @class */ (function () { + function HandlerBase(component, container, navigator) { + this._component = component; + this._container = container; + this._navigator = navigator; + this._enabled = false; + } + Object.defineProperty(HandlerBase.prototype, "isEnabled", { + /** + * Returns a Boolean indicating whether the interaction is enabled. + * + * @returns {boolean} `true` if the interaction is enabled. + */ + get: function () { + return this._enabled; }, enumerable: true, configurable: true }); - RenderTag.prototype._projectToCanvas = function (point3d, projectionMatrix) { - var projected = new THREE.Vector3(point3d.x, point3d.y, point3d.z) - .applyProjection(projectionMatrix); - return [(projected.x + 1) / 2, (-projected.y + 1) / 2]; + /** + * Enables the interaction. + * + * @example ```..enable();``` + */ + HandlerBase.prototype.enable = function () { + if (this._enabled || !this._component.activated) { + return; + } + this._enable(); + this._enabled = true; + this._component.configure(this._getConfiguration(true)); + }; + /** + * Disables the interaction. + * + * @example ```..disable();``` + */ + HandlerBase.prototype.disable = function () { + if (!this._enabled) { + return; + } + this._disable(); + this._enabled = false; + if (this._component.activated) { + this._component.configure(this._getConfiguration(false)); + } + }; + return HandlerBase; +}()); +exports.HandlerBase = HandlerBase; +exports.default = HandlerBase; + +},{}],383:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var Component_1 = require("../../Component"); +var MeshFactory = /** @class */ (function () { + function MeshFactory(imagePlaneDepth, imageSphereRadius) { + this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200; + this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200; + } + MeshFactory.prototype.createMesh = function (node, transform) { + var mesh = node.pano ? + this._createImageSphere(node, transform) : + this._createImagePlane(node, transform); + return mesh; + }; + MeshFactory.prototype.createScaledFlatMesh = function (node, transform, dx, dy) { + var texture = this._createTexture(node.image); + var materialParameters = this._createPlaneMaterialParameters(transform, texture); + var material = new THREE.ShaderMaterial(materialParameters); + var geometry = this._getFlatImagePlaneGeo(transform, dx, dy); + return new THREE.Mesh(geometry, material); + }; + MeshFactory.prototype.createFlatMesh = function (node, transform, basicX0, basicX1, basicY0, basicY1) { + var texture = this._createTexture(node.image); + var materialParameters = this._createPlaneMaterialParameters(transform, texture); + var material = new THREE.ShaderMaterial(materialParameters); + var geometry = this._getFlatImagePlaneGeoFromBasic(transform, basicX0, basicX1, basicY0, basicY1); + return new THREE.Mesh(geometry, material); + }; + MeshFactory.prototype.createCurtainMesh = function (node, transform) { + if (node.pano && !node.fullPano) { + throw new Error("Cropped panoramas cannot have curtain."); + } + return node.pano ? + this._createSphereCurtainMesh(node, transform) : + this._createCurtainMesh(node, transform); + }; + MeshFactory.prototype._createCurtainMesh = function (node, transform) { + var texture = this._createTexture(node.image); + var materialParameters = this._createCurtainPlaneMaterialParameters(transform, texture); + var material = new THREE.ShaderMaterial(materialParameters); + var geometry = this._useMesh(transform, node) ? + this._getImagePlaneGeo(transform, node) : + this._getRegularFlatImagePlaneGeo(transform); + return new THREE.Mesh(geometry, material); + }; + MeshFactory.prototype._createSphereCurtainMesh = function (node, transform) { + var texture = this._createTexture(node.image); + var materialParameters = this._createCurtainSphereMaterialParameters(transform, texture); + var material = new THREE.ShaderMaterial(materialParameters); + return this._useMesh(transform, node) ? + new THREE.Mesh(this._getImageSphereGeo(transform, node), material) : + new THREE.Mesh(this._getFlatImageSphereGeo(transform), material); + }; + MeshFactory.prototype._createImageSphere = function (node, transform) { + var texture = this._createTexture(node.image); + var materialParameters = this._createSphereMaterialParameters(transform, texture); + var material = new THREE.ShaderMaterial(materialParameters); + var mesh = this._useMesh(transform, node) ? + new THREE.Mesh(this._getImageSphereGeo(transform, node), material) : + new THREE.Mesh(this._getFlatImageSphereGeo(transform), material); + return mesh; + }; + MeshFactory.prototype._createImagePlane = function (node, transform) { + var texture = this._createTexture(node.image); + var materialParameters = this._createPlaneMaterialParameters(transform, texture); + var material = new THREE.ShaderMaterial(materialParameters); + var geometry = this._useMesh(transform, node) ? + this._getImagePlaneGeo(transform, node) : + this._getRegularFlatImagePlaneGeo(transform); + return new THREE.Mesh(geometry, material); + }; + MeshFactory.prototype._createSphereMaterialParameters = function (transform, texture) { + var gpano = transform.gpano; + var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2; + var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels; + var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels; + var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2; + var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels; + var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels; + var materialParameters = { + depthWrite: false, + fragmentShader: Component_1.Shaders.equirectangular.fragment, + side: THREE.DoubleSide, + transparent: true, + uniforms: { + opacity: { + type: "f", + value: 1, + }, + phiLength: { + type: "f", + value: phiLength, + }, + phiShift: { + type: "f", + value: phiShift, + }, + projectorMat: { + type: "m4", + value: transform.rt, + }, + projectorTex: { + type: "t", + value: texture, + }, + thetaLength: { + type: "f", + value: thetaLength, + }, + thetaShift: { + type: "f", + value: thetaShift, + }, + }, + vertexShader: Component_1.Shaders.equirectangular.vertex, + }; + return materialParameters; }; - RenderTag.prototype._convertToCameraSpace = function (point3d, matrixWorldInverse) { - return new THREE.Vector3(point3d[0], point3d[1], point3d[2]).applyMatrix4(matrixWorldInverse); + MeshFactory.prototype._createCurtainSphereMaterialParameters = function (transform, texture) { + var gpano = transform.gpano; + var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2; + var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels; + var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels; + var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2; + var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels; + var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels; + var materialParameters = { + depthWrite: false, + fragmentShader: Component_1.Shaders.equirectangularCurtain.fragment, + side: THREE.DoubleSide, + transparent: true, + uniforms: { + curtain: { + type: "f", + value: 1, + }, + opacity: { + type: "f", + value: 1, + }, + phiLength: { + type: "f", + value: phiLength, + }, + phiShift: { + type: "f", + value: phiShift, + }, + projectorMat: { + type: "m4", + value: transform.rt, + }, + projectorTex: { + type: "t", + value: texture, + }, + thetaLength: { + type: "f", + value: thetaLength, + }, + thetaShift: { + type: "f", + value: thetaShift, + }, + }, + vertexShader: Component_1.Shaders.equirectangularCurtain.vertex, + }; + return materialParameters; }; - return RenderTag; -}()); -exports.RenderTag = RenderTag; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = RenderTag; - -},{"rxjs/Subject":33,"three":157}],266:[function(require,module,exports){ -/// -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var vd = require("virtual-dom"); -var Component_1 = require("../../../Component"); -var Viewer_1 = require("../../../Viewer"); -/** - * @class SpotRenderTag - * @classdesc Tag visualizing the properties of a SpotTag. - */ -var SpotRenderTag = (function (_super) { - __extends(SpotRenderTag, _super); - function SpotRenderTag() { - _super.apply(this, arguments); - } - SpotRenderTag.prototype.dispose = function () { return; }; - SpotRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) { - var _this = this; - var vNodes = []; - var centroid3d = this._tag.geometry.getCentroid3d(this._transform); - var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse); - if (centroidCameraSpace.z < 0) { - var centroidCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix); - var centroidCss = centroidCanvas.map(function (coord) { return (100 * coord) + "%"; }); - var interactNone = function (e) { - _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag }); - }; - if (this._tag.icon != null) { - if (atlas.loaded) { - var sprite = atlas.getDOMSprite(this._tag.icon, Viewer_1.SpriteAlignment.Center, Viewer_1.SpriteAlignment.End); - var properties = { - onmousedown: interactNone, - style: { - bottom: 100 * (1 - centroidCanvas[1]) + "%", - left: centroidCss[0], - pointerEvents: "all", - position: "absolute", - transform: "translate(0px, -8px)", - }, - }; - vNodes.push(vd.h("div", properties, [sprite])); - } - } - else if (this._tag.text != null) { - var properties = { - onmousedown: interactNone, - style: { - bottom: 100 * (1 - centroidCanvas[1]) + "%", - color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6), - left: centroidCss[0], - pointerEvents: "all", - position: "absolute", - transform: "translate(-50%, -7px)", - }, - textContent: this._tag.text, - }; - vNodes.push(vd.h("span.TagSymbol", properties, [])); - } - var interact = this._interact(Component_1.TagOperation.Centroid); - var background = "#" + ("000000" + this._tag.color.toString(16)).substr(-6); - if (this._tag.editable) { - var interactorProperties = { - onmousedown: interact, - style: { - background: background, - left: centroidCss[0], - pointerEvents: "all", - position: "absolute", - top: centroidCss[1], - }, - }; - vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, [])); - } - var pointProperties = { - style: { - background: background, - left: centroidCss[0], - position: "absolute", - top: centroidCss[1], + MeshFactory.prototype._createPlaneMaterialParameters = function (transform, texture) { + var materialParameters = { + depthWrite: false, + fragmentShader: Component_1.Shaders.perspective.fragment, + side: THREE.DoubleSide, + transparent: true, + uniforms: { + opacity: { + type: "f", + value: 1, }, - }; - vNodes.push(vd.h("div.TagVertex", pointProperties, [])); + projectorMat: { + type: "m4", + value: transform.projectorMatrix(), + }, + projectorTex: { + type: "t", + value: texture, + }, + }, + vertexShader: Component_1.Shaders.perspective.vertex, + }; + return materialParameters; + }; + MeshFactory.prototype._createCurtainPlaneMaterialParameters = function (transform, texture) { + var materialParameters = { + depthWrite: false, + fragmentShader: Component_1.Shaders.perspectiveCurtain.fragment, + side: THREE.DoubleSide, + transparent: true, + uniforms: { + curtain: { + type: "f", + value: 1, + }, + opacity: { + type: "f", + value: 1, + }, + projectorMat: { + type: "m4", + value: transform.projectorMatrix(), + }, + projectorTex: { + type: "t", + value: texture, + }, + }, + vertexShader: Component_1.Shaders.perspective.vertex, + }; + return materialParameters; + }; + MeshFactory.prototype._createTexture = function (image) { + var texture = new THREE.Texture(image); + texture.minFilter = THREE.LinearFilter; + texture.needsUpdate = true; + return texture; + }; + MeshFactory.prototype._useMesh = function (transform, node) { + return node.mesh.vertices.length && transform.hasValidScale; + }; + MeshFactory.prototype._getImageSphereGeo = function (transform, node) { + var t = new THREE.Matrix4().getInverse(transform.srt); + // push everything at least 5 meters in front of the camera + var minZ = 5.0 * transform.scale; + var maxZ = this._imageSphereRadius * transform.scale; + var vertices = node.mesh.vertices; + var numVertices = vertices.length / 3; + var positions = new Float32Array(vertices.length); + for (var i = 0; i < numVertices; ++i) { + var index = 3 * i; + var x = vertices[index + 0]; + var y = vertices[index + 1]; + var z = vertices[index + 2]; + var l = Math.sqrt(x * x + y * y + z * z); + var boundedL = Math.max(minZ, Math.min(l, maxZ)); + var factor = boundedL / l; + var p = new THREE.Vector3(x * factor, y * factor, z * factor); + p.applyMatrix4(t); + positions[index + 0] = p.x; + positions[index + 1] = p.y; + positions[index + 2] = p.z; } - return vNodes; + var faces = node.mesh.faces; + var indices = new Uint16Array(faces.length); + for (var i = 0; i < faces.length; ++i) { + indices[i] = faces[i]; + } + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); + geometry.setIndex(new THREE.BufferAttribute(indices, 1)); + return geometry; + }; + MeshFactory.prototype._getImagePlaneGeo = function (transform, node) { + var t = new THREE.Matrix4().getInverse(transform.srt); + // push everything at least 5 meters in front of the camera + var minZ = 5.0 * transform.scale; + var maxZ = this._imagePlaneDepth * transform.scale; + var vertices = node.mesh.vertices; + var numVertices = vertices.length / 3; + var positions = new Float32Array(vertices.length); + for (var i = 0; i < numVertices; ++i) { + var index = 3 * i; + var x = vertices[index + 0]; + var y = vertices[index + 1]; + var z = vertices[index + 2]; + var boundedZ = Math.max(minZ, Math.min(z, maxZ)); + var factor = boundedZ / z; + var p = new THREE.Vector3(x * factor, y * factor, boundedZ); + p.applyMatrix4(t); + positions[index + 0] = p.x; + positions[index + 1] = p.y; + positions[index + 2] = p.z; + } + var faces = node.mesh.faces; + var indices = new Uint16Array(faces.length); + for (var i = 0; i < faces.length; ++i) { + indices[i] = faces[i]; + } + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); + geometry.setIndex(new THREE.BufferAttribute(indices, 1)); + return geometry; }; - SpotRenderTag.prototype._interact = function (operation, vertexIndex) { - var _this = this; - return function (e) { - var offsetX = e.offsetX - e.target.offsetWidth / 2; - var offsetY = e.offsetY - e.target.offsetHeight / 2; - _this._interact$.next({ - offsetX: offsetX, - offsetY: offsetY, - operation: operation, - tag: _this._tag, - vertexIndex: vertexIndex, - }); - }; + MeshFactory.prototype._getFlatImageSphereGeo = function (transform) { + var gpano = transform.gpano; + var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels; + var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels; + var thetaStart = Math.PI * + (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) / + gpano.FullPanoHeightPixels; + var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels; + var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength); + geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt)); + return geometry; }; - return SpotRenderTag; -}(Component_1.RenderTag)); -exports.SpotRenderTag = SpotRenderTag; + MeshFactory.prototype._getRegularFlatImagePlaneGeo = function (transform) { + var width = transform.width; + var height = transform.height; + var size = Math.max(width, height); + var dx = width / 2.0 / size; + var dy = height / 2.0 / size; + return this._getFlatImagePlaneGeo(transform, dx, dy); + }; + MeshFactory.prototype._getFlatImagePlaneGeo = function (transform, dx, dy) { + var vertices = []; + vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth)); + vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth)); + vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth)); + vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth)); + return this._createFlatGeometry(vertices); + }; + MeshFactory.prototype._getFlatImagePlaneGeoFromBasic = function (transform, basicX0, basicX1, basicY0, basicY1) { + var vertices = []; + vertices.push(transform.unprojectBasic([basicX0, basicY0], this._imagePlaneDepth)); + vertices.push(transform.unprojectBasic([basicX1, basicY0], this._imagePlaneDepth)); + vertices.push(transform.unprojectBasic([basicX1, basicY1], this._imagePlaneDepth)); + vertices.push(transform.unprojectBasic([basicX0, basicY1], this._imagePlaneDepth)); + return this._createFlatGeometry(vertices); + }; + MeshFactory.prototype._createFlatGeometry = function (vertices) { + var positions = new Float32Array(12); + for (var i = 0; i < vertices.length; i++) { + var index = 3 * i; + positions[index + 0] = vertices[i][0]; + positions[index + 1] = vertices[i][1]; + positions[index + 2] = vertices[i][2]; + } + var indices = new Uint16Array(6); + indices[0] = 0; + indices[1] = 1; + indices[2] = 3; + indices[3] = 1; + indices[4] = 2; + indices[5] = 3; + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3)); + geometry.setIndex(new THREE.BufferAttribute(indices, 1)); + return geometry; + }; + return MeshFactory; +}()); +exports.MeshFactory = MeshFactory; +exports.default = MeshFactory; -},{"../../../Component":207,"../../../Viewer":216,"virtual-dom":163}],267:[function(require,module,exports){ +},{"../../Component":290,"three":240}],384:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var Component_1 = require("../../../Component"); -/** - * @class SpotTag - * @classdesc Tag holding properties for visualizing the centroid of a geometry. - */ -var SpotTag = (function (_super) { - __extends(SpotTag, _super); - /** - * Create a spot tag. - * - * @override - * @constructor - * @param {string} id - * @param {Geometry} geometry - * @param {IOutlineTagOptions} options - Options defining the visual appearance and - * behavior of the spot tag. - */ - function SpotTag(id, geometry, options) { - _super.call(this, id, geometry); - this._color = options.color == null ? 0xFFFFFF : options.color; - this._editable = options.editable == null ? false : options.editable; - this._icon = options.icon === undefined ? null : options.icon; - this._text = options.text === undefined ? null : options.text; - this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var MeshScene = /** @class */ (function () { + function MeshScene() { + this.scene = new THREE.Scene(); + this.sceneOld = new THREE.Scene(); + this.imagePlanes = []; + this.imagePlanesOld = []; } - Object.defineProperty(SpotTag.prototype, "color", { - /** - * Get color property. - * @returns {number} The color of the spot as a hexagonal number; - */ - get: function () { - return this._color; - }, - /** - * Set color property. - * @param {number} - * - * @fires Tag#changed - */ - set: function (value) { - this._color = value; - this._notifyChanged$.next(this); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SpotTag.prototype, "editable", { - /** - * Get editable property. - * @returns {boolean} Value indicating if tag is editable. - */ - get: function () { - return this._editable; - }, - /** - * Set editable property. - * @param {boolean} - * - * @fires Tag#changed - */ - set: function (value) { - this._editable = value; - this._notifyChanged$.next(this); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SpotTag.prototype, "icon", { - /** - * Get icon property. - * @returns {string} - */ - get: function () { - return this._icon; - }, - /** - * Set icon property. - * @param {string} - * - * @fires Tag#changed - */ - set: function (value) { - this._icon = value; - this._notifyChanged$.next(this); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SpotTag.prototype, "text", { - /** - * Get text property. - * @returns {string} - */ - get: function () { - return this._text; - }, - /** - * Set text property. - * @param {string} - * - * @fires Tag#changed - */ - set: function (value) { - this._text = value; - this._notifyChanged$.next(this); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SpotTag.prototype, "textColor", { - /** - * Get text color property. - * @returns {number} - */ - get: function () { - return this._textColor; - }, - /** - * Set text color property. - * @param {number} - * - * @fires Tag#changed - */ - set: function (value) { - this._textColor = value; - this._notifyChanged$.next(this); - }, - enumerable: true, - configurable: true - }); - /** - * Set options for tag. - * - * @description Sets all the option properties provided and keps - * the rest of the values as is. - * - * @param {ISpotTagOptions} options - Spot tag options - * - * @fires {Tag#changed} - */ - SpotTag.prototype.setOptions = function (options) { - this._color = options.color == null ? this._color : options.color; - this._editable = options.editable == null ? this._editable : options.editable; - this._icon = options.icon === undefined ? this._icon : options.icon; - this._text = options.text === undefined ? this._text : options.text; - this._textColor = options.textColor == null ? this._textColor : options.textColor; - this._notifyChanged$.next(this); + MeshScene.prototype.updateImagePlanes = function (planes) { + this._dispose(this.imagePlanesOld, this.sceneOld); + for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) { + var plane = _a[_i]; + this.scene.remove(plane); + this.sceneOld.add(plane); + } + for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) { + var plane = planes_1[_b]; + this.scene.add(plane); + } + this.imagePlanesOld = this.imagePlanes; + this.imagePlanes = planes; + }; + MeshScene.prototype.addImagePlanes = function (planes) { + for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) { + var plane = planes_2[_i]; + this.scene.add(plane); + this.imagePlanes.push(plane); + } + }; + MeshScene.prototype.addImagePlanesOld = function (planes) { + for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) { + var plane = planes_3[_i]; + this.sceneOld.add(plane); + this.imagePlanesOld.push(plane); + } + }; + MeshScene.prototype.setImagePlanes = function (planes) { + this._clear(); + this.addImagePlanes(planes); + }; + MeshScene.prototype.setImagePlanesOld = function (planes) { + this._clearOld(); + this.addImagePlanesOld(planes); + }; + MeshScene.prototype.clear = function () { + this._clear(); + this._clearOld(); + }; + MeshScene.prototype._clear = function () { + this._dispose(this.imagePlanes, this.scene); + this.imagePlanes.length = 0; + }; + MeshScene.prototype._clearOld = function () { + this._dispose(this.imagePlanesOld, this.sceneOld); + this.imagePlanesOld.length = 0; + }; + MeshScene.prototype._dispose = function (planes, scene) { + for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) { + var plane = planes_4[_i]; + scene.remove(plane); + plane.geometry.dispose(); + plane.material.dispose(); + var texture = plane.material.uniforms.projectorTex.value; + if (texture != null) { + texture.dispose(); + } + } }; - return SpotTag; -}(Component_1.Tag)); -exports.SpotTag = SpotTag; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SpotTag; + return MeshScene; +}()); +exports.MeshScene = MeshScene; +exports.default = MeshScene; -},{"../../../Component":207}],268:[function(require,module,exports){ +},{"three":240}],385:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var vd = require("virtual-dom"); +var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/share"); -var Utils_1 = require("../../../Utils"); -/** - * @class Tag - * @abstract - * @classdesc Abstract class representing the basic functionality of for a tag. - */ -var Tag = (function (_super) { - __extends(Tag, _super); - /** - * Create a tag. - * - * @constructor - * @param {string} id - * @param {Geometry} geometry - */ - function Tag(id, geometry) { +var Component_1 = require("../../Component"); +var Geo_1 = require("../../Geo"); +var State_1 = require("../../State"); +var ZoomComponent = /** @class */ (function (_super) { + __extends(ZoomComponent, _super); + function ZoomComponent(name, container, navigator) { + var _this = _super.call(this, name, container, navigator) || this; + _this._viewportCoords = new Geo_1.ViewportCoords(); + _this._zoomDelta$ = new Subject_1.Subject(); + return _this; + } + ZoomComponent.prototype._activate = function () { var _this = this; - _super.call(this); - this._id = id; - this._geometry = geometry; - this._notifyChanged$ = new Subject_1.Subject(); - this._notifyChanged$ - .subscribe(function (t) { - _this.fire(Tag.changed, _this); - }); - this._geometry.changed$ - .subscribe(function (g) { - _this.fire(Tag.geometrychanged, _this); + this._renderSubscription = Observable_1.Observable + .combineLatest(this._navigator.stateService.currentState$, this._navigator.stateService.state$) + .map(function (_a) { + var frame = _a[0], state = _a[1]; + return [frame.state.zoom, state]; + }) + .map(function (_a) { + var zoom = _a[0], state = _a[1]; + var zoomInIcon = vd.h("div.ZoomInIcon", []); + var zoomInButton = zoom >= 3 || state === State_1.State.Waiting ? + vd.h("div.ZoomInButtonDisabled", [zoomInIcon]) : + vd.h("div.ZoomInButton", { onclick: function () { _this._zoomDelta$.next(1); } }, [zoomInIcon]); + var zoomOutIcon = vd.h("div.ZoomOutIcon", []); + var zoomOutButton = zoom <= 0 || state === State_1.State.Waiting ? + vd.h("div.ZoomOutButtonDisabled", [zoomOutIcon]) : + vd.h("div.ZoomOutButton", { onclick: function () { _this._zoomDelta$.next(-1); } }, [zoomOutIcon]); + return { + name: _this._name, + vnode: vd.h("div.ZoomContainer", { oncontextmenu: function (event) { event.preventDefault(); } }, [zoomInButton, zoomOutButton]), + }; + }) + .subscribe(this._container.domRenderer.render$); + this._zoomSubscription = this._zoomDelta$ + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .subscribe(function (_a) { + var zoomDelta = _a[0], render = _a[1], transform = _a[2]; + var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective); + var reference = transform.projectBasic(unprojected.toArray()); + _this._navigator.stateService.zoomIn(zoomDelta, reference); }); - } - Object.defineProperty(Tag.prototype, "id", { - /** - * Get id property. - * @returns {string} - */ - get: function () { - return this._id; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tag.prototype, "geometry", { - /** - * Get geometry property. - * @returns {Geometry} - */ - get: function () { - return this._geometry; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tag.prototype, "changed$", { - /** - * Get changed observable. - * @returns {Observable} - */ - get: function () { - return this._notifyChanged$; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tag.prototype, "geometryChanged$", { - /** - * Get geometry changed observable. - * @returns {Observable} - */ - get: function () { - var _this = this; - return this._geometry.changed$ - .map(function (geometry) { - return _this; - }) - .share(); - }, - enumerable: true, - configurable: true - }); - /** - * Event fired when a property related to the visual appearance of the - * tag has changed. - * - * @event Tag#changed - * @type {Tag} The tag instance that has changed. - */ - Tag.changed = "changed"; - /** - * Event fired when the geometry of the tag has changed. - * - * @event Tag#geometrychanged - * @type {Tag} The tag instance whose geometry has changed. - */ - Tag.geometrychanged = "geometrychanged"; - return Tag; -}(Utils_1.EventEmitter)); -exports.Tag = Tag; + }; + ZoomComponent.prototype._deactivate = function () { + this._renderSubscription.unsubscribe(); + this._zoomSubscription.unsubscribe(); + }; + ZoomComponent.prototype._getDefaultConfiguration = function () { + return {}; + }; + ZoomComponent.componentName = "zoom"; + return ZoomComponent; +}(Component_1.Component)); +exports.ZoomComponent = ZoomComponent; +Component_1.ComponentService.register(ZoomComponent); +exports.default = ZoomComponent; + +},{"../../Component":290,"../../Geo":293,"../../State":297,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],386:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Tag; +var MapillaryError_1 = require("./MapillaryError"); +/** + * @class AbortMapillaryError + * + * @classdesc Error thrown when a move to request has been + * aborted before completing because of a subsequent request. + */ +var AbortMapillaryError = /** @class */ (function (_super) { + __extends(AbortMapillaryError, _super); + function AbortMapillaryError(message) { + var _this = _super.call(this, message != null ? message : "The request was aborted.") || this; + Object.setPrototypeOf(_this, AbortMapillaryError.prototype); + _this.name = "AbortMapillaryError"; + return _this; + } + return AbortMapillaryError; +}(MapillaryError_1.MapillaryError)); +exports.AbortMapillaryError = AbortMapillaryError; +exports.default = AbortMapillaryError; -},{"../../../Utils":215,"rxjs/Subject":33,"rxjs/add/operator/map":60,"rxjs/add/operator/share":69}],269:[function(require,module,exports){ +},{"./MapillaryError":389}],387:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var MapillaryError_1 = require("./MapillaryError"); -var ArgumentMapillaryError = (function (_super) { +var ArgumentMapillaryError = /** @class */ (function (_super) { __extends(ArgumentMapillaryError, _super); function ArgumentMapillaryError(message) { - _super.call(this); - this.name = "ArgumentMapillaryError"; - this.message = message != null ? message : "The argument is not valid."; + var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this; + Object.setPrototypeOf(_this, ArgumentMapillaryError.prototype); + _this.name = "ArgumentMapillaryError"; + return _this; } return ArgumentMapillaryError; }(MapillaryError_1.MapillaryError)); exports.ArgumentMapillaryError = ArgumentMapillaryError; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = ArgumentMapillaryError; -},{"./MapillaryError":272}],270:[function(require,module,exports){ +},{"./MapillaryError":389}],388:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var MapillaryError_1 = require("./MapillaryError"); -var GraphMapillaryError = (function (_super) { +var GraphMapillaryError = /** @class */ (function (_super) { __extends(GraphMapillaryError, _super); function GraphMapillaryError(message) { - _super.call(this); - this.name = "GraphMapillaryError"; - this.message = message; + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, GraphMapillaryError.prototype); + _this.name = "GraphMapillaryError"; + return _this; } return GraphMapillaryError; }(MapillaryError_1.MapillaryError)); exports.GraphMapillaryError = GraphMapillaryError; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = GraphMapillaryError; -},{"./MapillaryError":272}],271:[function(require,module,exports){ +},{"./MapillaryError":389}],389:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var MapillaryError_1 = require("./MapillaryError"); -var InitializationMapillaryError = (function (_super) { - __extends(InitializationMapillaryError, _super); - function InitializationMapillaryError() { - _super.call(this); - this.name = "InitializationMapillaryError"; - this.message = "Could not initialize"; - } - return InitializationMapillaryError; -}(MapillaryError_1.MapillaryError)); -exports.InitializationMapillaryError = InitializationMapillaryError; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = InitializationMapillaryError; - -},{"./MapillaryError":272}],272:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var MapillaryError = (function (_super) { +var MapillaryError = /** @class */ (function (_super) { __extends(MapillaryError, _super); - function MapillaryError() { - _super.call(this); - // fixme ERROR have not loaded correct props - // this.stack = (new Error()).stack; + function MapillaryError(message) { + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, MapillaryError.prototype); + _this.name = "MapillaryError"; + return _this; } return MapillaryError; }(Error)); exports.MapillaryError = MapillaryError; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = MapillaryError; -},{}],273:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var MapillaryError_1 = require("./MapillaryError"); -var MoveTypeMapillaryError = (function (_super) { - __extends(MoveTypeMapillaryError, _super); - function MoveTypeMapillaryError() { - _super.call(this); - this.name = "MoveTypeMapillaryError"; - this.message = "The type of ui you use does not support this move"; - } - return MoveTypeMapillaryError; -}(MapillaryError_1.MapillaryError)); -exports.MoveTypeMapillaryError = MoveTypeMapillaryError; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = MoveTypeMapillaryError; - -},{"./MapillaryError":272}],274:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var MapillaryError_1 = require("./MapillaryError"); -var NotImplementedMapillaryError = (function (_super) { - __extends(NotImplementedMapillaryError, _super); - function NotImplementedMapillaryError() { - _super.call(this); - this.name = "NotImplementedMapillaryError"; - this.message = "This function has not yet been implemented"; - } - return NotImplementedMapillaryError; -}(MapillaryError_1.MapillaryError)); -exports.NotImplementedMapillaryError = NotImplementedMapillaryError; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = NotImplementedMapillaryError; - -},{"./MapillaryError":272}],275:[function(require,module,exports){ +},{}],390:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var MapillaryError_1 = require("./MapillaryError"); -var ParameterMapillaryError = (function (_super) { - __extends(ParameterMapillaryError, _super); - function ParameterMapillaryError(message) { - _super.call(this); - this.name = "ParameterMapillaryError"; - this.message = message != null ? message : "The function was not called with correct parameters"; - } - return ParameterMapillaryError; -}(MapillaryError_1.MapillaryError)); -exports.ParameterMapillaryError = ParameterMapillaryError; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ParameterMapillaryError; - -},{"./MapillaryError":272}],276:[function(require,module,exports){ /// -"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); /** * @class Camera * * @classdesc Holds information about a camera. */ -var Camera = (function () { +var Camera = /** @class */ (function () { /** * Create a new camera instance. * @param {Transform} [transform] - Optional transform instance. @@ -25894,20 +36160,27 @@ var Camera = (function () { /** * Get the focal length based on the transform. * - * @description Returns 0.5 focal length if transform has gpano - * information. + * @description Returns the focal length of the transform if gpano info is not available. + * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on + * the gpano information if available. * * @returns {number} Focal length. */ Camera.prototype._getFocal = function (transform) { - return transform.gpano == null ? transform.focal : 0.5; + if (transform.gpano == null) { + return transform.focal; + } + var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels; + var focal = 0.5 / Math.tan(vFov / 2); + return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal)); }; return Camera; }()); exports.Camera = Camera; -},{"three":157}],277:[function(require,module,exports){ +},{"three":240}],391:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); /** * @class GeoCoords * @@ -25977,7 +36250,7 @@ exports.Camera = Camera; * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in * the first step for both conversions. */ -var GeoCoords = (function () { +var GeoCoords = /** @class */ (function () { function GeoCoords() { this._wgs84a = 6378137.0; this._wgs84b = 6356752.31424518; @@ -26127,26 +36400,37 @@ var GeoCoords = (function () { return GeoCoords; }()); exports.GeoCoords = GeoCoords; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = GeoCoords; -},{}],278:[function(require,module,exports){ -/// +},{}],392:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); /** * @class Spatial * * @classdesc Provides methods for scalar, vector and matrix calculations. */ -var Spatial = (function () { +var Spatial = /** @class */ (function () { function Spatial() { this._epsilon = 1e-9; } + /** + * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to + * bearing (clockwise with origin at north or Y-axis). + * + * @param {number} phi - Azimuthal phi angle in radians. + * @returns {number} Bearing in radians. + */ + Spatial.prototype.azimuthalToBearing = function (phi) { + return -phi + Math.PI / 2; + }; /** * Converts degrees to radians. * - * @param {number} deg Degrees. + * @param {number} deg - Degrees. + * @returns {number} Radians. */ Spatial.prototype.degToRad = function (deg) { return Math.PI * deg / 180; @@ -26154,7 +36438,8 @@ var Spatial = (function () { /** * Converts radians to degrees. * - * @param {number} rad Radians. + * @param {number} rad - Radians. + * @returns {number} Degrees. */ Spatial.prototype.radToDeg = function (rad) { return 180 * rad / Math.PI; @@ -26162,19 +36447,23 @@ var Spatial = (function () { /** * Creates a rotation matrix from an angle-axis vector. * - * @param {Array} angleAxis Angle-axis representation of a rotation. + * @param {Array} angleAxis - Angle-axis representation of a rotation. + * @returns {THREE.Matrix4} Rotation matrix. */ Spatial.prototype.rotationMatrix = function (angleAxis) { var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]); var angle = axis.length(); - axis.normalize(); + if (angle > 0) { + axis.normalize(); + } return new THREE.Matrix4().makeRotationAxis(axis, angle); }; /** * Rotates a vector according to a angle-axis rotation vector. * - * @param {Array} vector Vector to rotate. - * @param {Array} angleAxis Angle-axis representation of a rotation. + * @param {Array} vector - Vector to rotate. + * @param {Array} angleAxis - Angle-axis representation of a rotation. + * @returns {THREE.Vector3} Rotated vector. */ Spatial.prototype.rotate = function (vector, angleAxis) { var v = new THREE.Vector3(vector[0], vector[1], vector[2]); @@ -26187,8 +36476,9 @@ var Spatial = (function () { * on the angle-axis representation and a translation vector * according to C = -R^T t. * - * @param {Array} rotation Angle-axis representation of a rotation. - * @param {Array} translation Translation vector. + * @param {Array} rotation - Angle-axis representation of a rotation. + * @param {Array} translation - Translation vector. + * @returns {THREE.Vector3} Optical center. */ Spatial.prototype.opticalCenter = function (rotation, translation) { var angleAxis = [-rotation[0], -rotation[1], -rotation[2]]; @@ -26199,7 +36489,8 @@ var Spatial = (function () { * Calculates the viewing direction from a rotation vector * on the angle-axis representation. * - * @param {number[]} rotation Angle-axis representation of a rotation. + * @param {number[]} rotation - Angle-axis representation of a rotation. + * @returns {THREE.Vector3} Viewing direction. */ Spatial.prototype.viewingDirection = function (rotation) { var angleAxis = [-rotation[0], -rotation[1], -rotation[2]]; @@ -26208,11 +36499,10 @@ var Spatial = (function () { /** * Wrap a number on the interval [min, max]. * - * @param {number} value Value to wrap. - * @param {number} min Lower endpoint of interval. - * @param {number} max Upper endpoint of interval. - * - * @returs {number} The wrapped number. + * @param {number} value - Value to wrap. + * @param {number} min - Lower endpoint of interval. + * @param {number} max - Upper endpoint of interval. + * @returns {number} The wrapped number. */ Spatial.prototype.wrap = function (value, min, max) { if (max < min) { @@ -26232,9 +36522,8 @@ var Spatial = (function () { /** * Wrap an angle on the interval [-Pi, Pi]. * - * @param {number} angle Value to wrap. - * - * @returs {number} The wrapped angle. + * @param {number} angle - Value to wrap. + * @returns {number} Wrapped angle. */ Spatial.prototype.wrapAngle = function (angle) { return this.wrap(angle, -Math.PI, Math.PI); @@ -26243,11 +36532,10 @@ var Spatial = (function () { * Limit the value to the interval [min, max] by changing the value to * the nearest available one when it is outside the interval. * - * @param {number} value Value to clamp. - * @param {number} min Minimum of the interval. - * @param {number} max Maximum of the interval. - * - * @returns {number} The clamped value. + * @param {number} value - Value to clamp. + * @param {number} min - Minimum of the interval. + * @param {number} max - Maximum of the interval. + * @returns {number} Clamped value. */ Spatial.prototype.clamp = function (value, min, max) { if (value < min) { @@ -26262,10 +36550,11 @@ var Spatial = (function () { * Calculates the counter-clockwise angle from the first * vector (x1, y1)^T to the second (x2, y2)^T. * - * @param {number} x1 X-value of first vector. - * @param {number} y1 Y-value of first vector. - * @param {number} x2 X-value of second vector. - * @param {number} y2 Y-value of second vector. + * @param {number} x1 - X coordinate of first vector. + * @param {number} y1 - Y coordinate of first vector. + * @param {number} x2 - X coordinate of second vector. + * @param {number} y2 - Y coordinate of second vector. + * @returns {number} Counter clockwise angle between the vectors. */ Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) { var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1); @@ -26275,8 +36564,9 @@ var Spatial = (function () { * Calculates the minimum (absolute) angle change for rotation * from one angle to another on the [-Pi, Pi] interval. * - * @param {number} angle1 The origin angle. - * @param {number} angle2 The destination angle. + * @param {number} angle1 - Start angle. + * @param {number} angle2 - Destination angle. + * @returns {number} Absolute angle change between angles. */ Spatial.prototype.angleDifference = function (angle1, angle2) { var angle = angle2 - angle1; @@ -26286,23 +36576,26 @@ var Spatial = (function () { * Calculates the relative rotation angle between two * angle-axis vectors. * - * @param {number} rotation1 First angle-axis vector. - * @param {number} rotation2 Second angle-axis vector. + * @param {number} rotation1 - First angle-axis vector. + * @param {number} rotation2 - Second angle-axis vector. + * @returns {number} Relative rotation angle. */ Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) { var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]); var R2 = this.rotationMatrix(rotation2); var R = R1T.multiply(R2); var elements = R.elements; - // from Tr(R) = 1 + 2*cos(theta) - var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2); + // from Tr(R) = 1 + 2 * cos(theta) + var tr = elements[0] + elements[5] + elements[10]; + var theta = Math.acos(Math.max(Math.min((tr - 1) / 2, 1), -1)); return theta; }; /** * Calculates the angle from a vector to a plane. * - * @param {Array} vector The vector. - * @param {Array} planeNormal Normal of the plane. + * @param {Array} vector - The vector. + * @param {Array} planeNormal - Normal of the plane. + * @returns {number} Angle from between plane and vector. */ Spatial.prototype.angleToPlane = function (vector, planeNormal) { var v = new THREE.Vector3().fromArray(vector); @@ -26318,17 +36611,18 @@ var Spatial = (function () { * (latitude longitude pairs) in meters according to * the haversine formula. * - * @param {number} lat1 The latitude of the first coordinate. - * @param {number} lon1 The longitude of the first coordinate. - * @param {number} lat2 The latitude of the second coordinate. - * @param {number} lon2 The longitude of the second coordinate. + * @param {number} lat1 - Latitude of the first coordinate in degrees. + * @param {number} lon1 - Longitude of the first coordinate in degrees. + * @param {number} lat2 - Latitude of the second coordinate in degrees. + * @param {number} lon2 - Longitude of the second coordinate in degrees. + * @returns {number} Distance between lat lon positions in meters. */ Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) { var r = 6371000; var dLat = this.degToRad(lat2 - lat1); var dLon = this.degToRad(lon2 - lon1); var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) + - Math.cos(lat1) * Math.cos(lat2) * + Math.cos(this.degToRad(lat1)) * Math.cos(this.degToRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav)); return d; @@ -26336,12 +36630,12 @@ var Spatial = (function () { return Spatial; }()); exports.Spatial = Spatial; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Spatial; -},{"three":157}],279:[function(require,module,exports){ -/// +},{"three":240}],393:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); /** * @class Transform @@ -26349,28 +36643,37 @@ var THREE = require("three"); * @classdesc Class used for calculating coordinate transformations * and projections. */ -var Transform = (function () { +var Transform = /** @class */ (function () { /** * Create a new transform instance. - * @param {Node} apiNavImIm - Node properties. - * @param {HTMLImageElement} image - Node image. - * @param {Array} translation - Node translation vector in three dimensions. + * @param {number} orientation - Image orientation. + * @param {number} width - Image height. + * @param {number} height - Image width. + * @param {number} focal - Focal length. + * @param {number} scale - Atomic scale. + * @param {IGPano} gpano - Panorama properties. + * @param {Array} rotation - Rotation vector in three dimensions. + * @param {Array} translation - Translation vector in three dimensions. + * @param {HTMLImageElement} image - Image for fallback size calculations. */ - function Transform(node, image, translation) { - this._orientation = this._getValue(node.orientation, 1); + function Transform(orientation, width, height, focal, scale, gpano, rotation, translation, image, textureScale) { + this._orientation = this._getValue(orientation, 1); var imageWidth = image != null ? image.width : 4; var imageHeight = image != null ? image.height : 3; var keepOrientation = this._orientation < 5; - this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight); - this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth); + this._width = this._getValue(width, keepOrientation ? imageWidth : imageHeight); + this._height = this._getValue(height, keepOrientation ? imageHeight : imageWidth); this._basicAspect = keepOrientation ? this._width / this._height : this._height / this._width; - this._focal = this._getValue(node.focal, 1); - this._scale = this._getValue(node.scale, 0); - this._gpano = node.gpano != null ? node.gpano : null; - this._rt = this._getRt(node.rotation, translation); + this._basicWidth = keepOrientation ? width : height; + this._basicHeight = keepOrientation ? height : width; + this._focal = this._getValue(focal, 1); + this._scale = this._getValue(scale, 0); + this._gpano = gpano != null ? gpano : null; + this._rt = this._getRt(rotation, translation); this._srt = this._getSrt(this._rt, this._scale); + this._textureScale = !!textureScale ? textureScale : [1, 1]; } Object.defineProperty(Transform.prototype, "basicAspect", { /** @@ -26383,6 +36686,38 @@ var Transform = (function () { enumerable: true, configurable: true }); + Object.defineProperty(Transform.prototype, "basicHeight", { + /** + * Get basic height. + * + * @description Does not fall back to node image height but + * uses original value from API so can be faulty. + * + * @returns {number} The height of the basic version image + * (adjusted for orientation). + */ + get: function () { + return this._basicHeight; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transform.prototype, "basicWidth", { + /** + * Get basic width. + * + * @description Does not fall back to node image width but + * uses original value from API so can be faulty. + * + * @returns {number} The width of the basic version image + * (adjusted for orientation). + */ + get: function () { + return this._basicWidth; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Transform.prototype, "focal", { /** * Get focal. @@ -26394,6 +36729,23 @@ var Transform = (function () { enumerable: true, configurable: true }); + Object.defineProperty(Transform.prototype, "fullPano", { + /** + * Get fullPano. + * + * @returns {boolean} Value indicating whether the node is a complete + * 360 panorama. + */ + get: function () { + return this._gpano != null && + this._gpano.CroppedAreaLeftPixels === 0 && + this._gpano.CroppedAreaTopPixels === 0 && + this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels && + this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Transform.prototype, "gpano", { /** * Get gpano. @@ -26408,6 +36760,10 @@ var Transform = (function () { Object.defineProperty(Transform.prototype, "height", { /** * Get height. + * + * @description Falls back to the node image height if + * the API data is faulty. + * * @returns {number} The orientation adjusted image height. */ get: function () { @@ -26460,9 +36816,24 @@ var Transform = (function () { enumerable: true, configurable: true }); + Object.defineProperty(Transform.prototype, "hasValidScale", { + /** + * Get has valid scale. + * @returns {boolean} Value indicating if the scale of the transform is valid. + */ + get: function () { + return this._scale > 1e-2 && this._scale < 50; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Transform.prototype, "width", { /** * Get width. + * + * @description Falls back to the node image width if + * the API data is faulty. + * * @returns {number} The orientation adjusted image width. */ get: function () { @@ -26621,10 +36992,18 @@ var Transform = (function () { ]; } else { - return [ - bearing[0] * this._focal / bearing[2], - bearing[1] * this._focal / bearing[2], - ]; + if (bearing[2] > 0) { + return [ + bearing[0] * this._focal / bearing[2], + bearing[1] * this._focal / bearing[2], + ]; + } + else { + return [ + bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + ]; + } } }; /** @@ -26737,7 +37116,9 @@ var Transform = (function () { Transform.prototype._getRt = function (rotation, translation) { var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]); var angle = axis.length(); - axis.normalize(); + if (angle > 0) { + axis.normalize(); + } var rt = new THREE.Matrix4(); rt.makeRotationAxis(axis, angle); rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2])); @@ -26768,8 +37149,10 @@ var Transform = (function () { */ Transform.prototype._normalizedToTextureMatrix = function () { var size = Math.max(this._width, this._height); - var w = size / this._width; - var h = size / this._height; + var scaleX = this._orientation < 5 ? this._textureScale[0] : this._textureScale[1]; + var scaleY = this._orientation < 5 ? this._textureScale[1] : this._textureScale[0]; + var w = size / this._width * scaleX; + var h = size / this._height * scaleY; switch (this._orientation) { case 1: return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1); @@ -26787,17 +37170,475 @@ var Transform = (function () { }()); exports.Transform = Transform; -},{"three":157}],280:[function(require,module,exports){ +},{"three":240}],394:[function(require,module,exports){ +"use strict"; /// +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +/** + * @class ViewportCoords + * + * @classdesc Provides methods for calculating 2D coordinate conversions + * as well as 3D projection and unprojection. + * + * Basic coordinates are 2D coordinates on the [0, 1] interval and + * have the origin point, (0, 0), at the top left corner and the + * maximum value, (1, 1), at the bottom right corner of the original + * image. + * + * Viewport coordinates are 2D coordinates on the [-1, 1] interval and + * have the origin point in the center. The bottom left corner point is + * (-1, -1) and the top right corner point is (1, 1). + * + * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and + * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left + * corner and the maximum value is (canvasWidth, canvasHeight) is in the + * bottom right corner. + * + * 3D coordinates are in the topocentric world reference frame. + */ +var ViewportCoords = /** @class */ (function () { + function ViewportCoords() { + this._unprojectDepth = 200; + } + /** + * Convert basic coordinates to canvas coordinates. + * + * @description Transform origin and camera position needs to be the + * equal for reliable return value. + * + * @param {number} basicX - Basic X coordinate. + * @param {number} basicY - Basic Y coordinate. + * @param {HTMLElement} container - The viewer container. + * @param {Transform} transform - Transform of the node to unproject from. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D canvas coordinates. + */ + ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) { + var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth); + var canvas = this.projectToCanvas(point3d, container, camera); + return canvas; + }; + /** + * Convert basic coordinates to canvas coordinates safely. If 3D point is + * behind camera null will be returned. + * + * @description Transform origin and camera position needs to be the + * equal for reliable return value. + * + * @param {number} basicX - Basic X coordinate. + * @param {number} basicY - Basic Y coordinate. + * @param {HTMLElement} container - The viewer container. + * @param {Transform} transform - Transform of the node to unproject from. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D canvas coordinates if the basic point represents a 3D point + * in front of the camera, otherwise null. + */ + ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) { + var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth); + var pointCamera = this.worldToCamera(point3d, camera); + if (pointCamera[2] > 0) { + return null; + } + var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1]; + var canvas = this.viewportToCanvas(viewportX, viewportY, container); + return canvas; + }; + /** + * Convert basic coordinates to viewport coordinates. + * + * @description Transform origin and camera position needs to be the + * equal for reliable return value. + * + * @param {number} basicX - Basic X coordinate. + * @param {number} basicY - Basic Y coordinate. + * @param {Transform} transform - Transform of the node to unproject from. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D viewport coordinates. + */ + ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) { + var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth); + var viewport = this.projectToViewport(point3d, camera); + return viewport; + }; + /** + * Convert camera 3D coordinates to viewport coordinates. + * + * @param {number} pointCamera - 3D point in camera coordinate system. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D viewport coordinates. + */ + ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) { + var viewport = new THREE.Vector3().fromArray(pointCamera) + .applyMatrix4(camera.projectionMatrix); + return [viewport.x, viewport.y]; + }; + /** + * Get canvas pixel position from event. + * + * @param {Event} event - Event containing clientX and clientY properties. + * @param {HTMLElement} element - HTML element. + * @returns {Array} 2D canvas coordinates. + */ + ViewportCoords.prototype.canvasPosition = function (event, element) { + var clientRect = element.getBoundingClientRect(); + var canvasX = event.clientX - clientRect.left - element.clientLeft; + var canvasY = event.clientY - clientRect.top - element.clientTop; + return [canvasX, canvasY]; + }; + /** + * Convert canvas coordinates to basic coordinates. + * + * @description Transform origin and camera position needs to be the + * equal for reliable return value. + * + * @param {number} canvasX - Canvas X coordinate. + * @param {number} canvasY - Canvas Y coordinate. + * @param {HTMLElement} container - The viewer container. + * @param {Transform} transform - Transform of the node to unproject from. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D basic coordinates. + */ + ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) { + var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera) + .toArray(); + var basic = transform.projectBasic(point3d); + return basic; + }; + /** + * Convert canvas coordinates to viewport coordinates. + * + * @param {number} canvasX - Canvas X coordinate. + * @param {number} canvasY - Canvas Y coordinate. + * @param {HTMLElement} container - The viewer container. + * @returns {Array} 2D viewport coordinates. + */ + ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) { + var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1]; + var viewportX = 2 * canvasX / canvasWidth - 1; + var viewportY = 1 - 2 * canvasY / canvasHeight; + return [viewportX, viewportY]; + }; + /** + * Determines the width and height of the container in canvas coordinates. + * + * @param {HTMLElement} container - The viewer container. + * @returns {Array} 2D canvas coordinates. + */ + ViewportCoords.prototype.containerToCanvas = function (container) { + return [container.offsetWidth, container.offsetHeight]; + }; + /** + * Determine basic distances from image to canvas corners. + * + * @description Transform origin and camera position needs to be the + * equal for reliable return value. + * + * Determines the smallest basic distance for every side of the canvas. + * + * @param {Transform} transform - Transform of the node to unproject from. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} Array of basic distances as [top, right, bottom, left]. + */ + ViewportCoords.prototype.getBasicDistances = function (transform, camera) { + var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera); + var topRightBasic = this.viewportToBasic(1, 1, transform, camera); + var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera); + var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera); + var topBasicDistance = 0; + var rightBasicDistance = 0; + var bottomBasicDistance = 0; + var leftBasicDistance = 0; + if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) { + topBasicDistance = topLeftBasic[1] > topRightBasic[1] ? + -topLeftBasic[1] : + -topRightBasic[1]; + } + if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) { + rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ? + topRightBasic[0] - 1 : + bottomRightBasic[0] - 1; + } + if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) { + bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ? + bottomRightBasic[1] - 1 : + bottomLeftBasic[1] - 1; + } + if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) { + leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ? + -bottomLeftBasic[0] : + -topLeftBasic[0]; + } + return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance]; + }; + /** + * Determine pixel distances from image to canvas corners. + * + * @description Transform origin and camera position needs to be the + * equal for reliable return value. + * + * Determines the smallest pixel distance for every side of the canvas. + * + * @param {HTMLElement} container - The viewer container. + * @param {Transform} transform - Transform of the node to unproject from. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} Array of pixel distances as [top, right, bottom, left]. + */ + ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) { + var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera); + var topRightBasic = this.viewportToBasic(1, 1, transform, camera); + var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera); + var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera); + var topPixelDistance = 0; + var rightPixelDistance = 0; + var bottomPixelDistance = 0; + var leftPixelDistance = 0; + var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1]; + if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) { + var basicX = topLeftBasic[1] > topRightBasic[1] ? + topLeftBasic[0] : + topRightBasic[0]; + var canvas = this.basicToCanvas(basicX, 0, container, transform, camera); + topPixelDistance = canvas[1] > 0 ? canvas[1] : 0; + } + if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) { + var basicY = topRightBasic[0] < bottomRightBasic[0] ? + topRightBasic[1] : + bottomRightBasic[1]; + var canvas = this.basicToCanvas(1, basicY, container, transform, camera); + rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0; + } + if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) { + var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ? + bottomRightBasic[0] : + bottomLeftBasic[0]; + var canvas = this.basicToCanvas(basicX, 1, container, transform, camera); + bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0; + } + if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) { + var basicY = bottomLeftBasic[0] > topLeftBasic[0] ? + bottomLeftBasic[1] : + topLeftBasic[1]; + var canvas = this.basicToCanvas(0, basicY, container, transform, camera); + leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0; + } + return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance]; + }; + /** + * Determine if an event occured inside an element. + * + * @param {Event} event - Event containing clientX and clientY properties. + * @param {HTMLElement} element - HTML element. + * @returns {boolean} Value indicating if the event occured inside the element or not. + */ + ViewportCoords.prototype.insideElement = function (event, element) { + var clientRect = element.getBoundingClientRect(); + var minX = clientRect.left + element.clientLeft; + var maxX = minX + element.clientWidth; + var minY = clientRect.top + element.clientTop; + var maxY = minY + element.clientHeight; + return event.clientX > minX && + event.clientX < maxX && + event.clientY > minY && + event.clientY < maxY; + }; + /** + * Project 3D world coordinates to canvas coordinates. + * + * @param {Array} point3D - 3D world coordinates. + * @param {HTMLElement} container - The viewer container. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D canvas coordinates. + */ + ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) { + var viewport = this.projectToViewport(point3d, camera); + var canvas = this.viewportToCanvas(viewport[0], viewport[1], container); + return canvas; + }; + /** + * Project 3D world coordinates to viewport coordinates. + * + * @param {Array} point3D - 3D world coordinates. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D viewport coordinates. + */ + ViewportCoords.prototype.projectToViewport = function (point3d, camera) { + var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2]) + .project(camera); + return [viewport.x, viewport.y]; + }; + /** + * Uproject canvas coordinates to 3D world coordinates. + * + * @param {number} canvasX - Canvas X coordinate. + * @param {number} canvasY - Canvas Y coordinate. + * @param {HTMLElement} container - The viewer container. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 3D world coordinates. + */ + ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) { + var viewport = this.canvasToViewport(canvasX, canvasY, container); + var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera); + return point3d; + }; + /** + * Unproject viewport coordinates to 3D world coordinates. + * + * @param {number} viewportX - Viewport X coordinate. + * @param {number} viewportY - Viewport Y coordinate. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 3D world coordinates. + */ + ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) { + var point3d = new THREE.Vector3(viewportX, viewportY, 1) + .unproject(camera); + return point3d; + }; + /** + * Convert viewport coordinates to basic coordinates. + * + * @description Transform origin and camera position needs to be the + * equal for reliable return value. + * + * @param {number} viewportX - Viewport X coordinate. + * @param {number} viewportY - Viewport Y coordinate. + * @param {Transform} transform - Transform of the node to unproject from. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 2D basic coordinates. + */ + ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) { + var point3d = new THREE.Vector3(viewportX, viewportY, 1) + .unproject(camera) + .toArray(); + var basic = transform.projectBasic(point3d); + return basic; + }; + /** + * Convert viewport coordinates to canvas coordinates. + * + * @param {number} viewportX - Viewport X coordinate. + * @param {number} viewportY - Viewport Y coordinate. + * @param {HTMLElement} container - The viewer container. + * @returns {Array} 2D canvas coordinates. + */ + ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) { + var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1]; + var canvasX = canvasWidth * (viewportX + 1) / 2; + var canvasY = -canvasHeight * (viewportY - 1) / 2; + return [canvasX, canvasY]; + }; + /** + * Convert 3D world coordinates to 3D camera coordinates. + * + * @param {number} point3D - 3D point in world coordinate system. + * @param {THREE.Camera} camera - Camera used in rendering. + * @returns {Array} 3D camera coordinates. + */ + ViewportCoords.prototype.worldToCamera = function (point3d, camera) { + var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2]) + .applyMatrix4(camera.matrixWorldInverse); + return pointCamera.toArray(); + }; + return ViewportCoords; +}()); +exports.ViewportCoords = ViewportCoords; +exports.default = ViewportCoords; + +},{"three":240}],395:[function(require,module,exports){ "use strict"; -var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/from"); -require("rxjs/add/operator/catch"); -require("rxjs/add/operator/do"); -require("rxjs/add/operator/finally"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/publish"); +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * @class Filter + * + * @classdesc Represents a class for creating node filters. Implementation and + * definitions based on https://github.com/mapbox/feature-filter. + */ +var FilterCreator = /** @class */ (function () { + function FilterCreator() { + } + /** + * Create a filter from a filter expression. + * + * @description The following filters are supported: + * + * Comparison + * `==` + * `!=` + * `<` + * `<=` + * `>` + * `>=` + * + * Set membership + * `in` + * `!in` + * + * Combining + * `all` + * + * @param {FilterExpression} filter - Comparison, set membership or combinding filter + * expression. + * @returns {FilterFunction} Function taking a node and returning a boolean that + * indicates whether the node passed the test or not. + */ + FilterCreator.prototype.createFilter = function (filter) { + return new Function("node", "return " + this._compile(filter) + ";"); + }; + FilterCreator.prototype._compile = function (filter) { + if (filter == null || filter.length <= 1) { + return "true"; + } + var operator = filter[0]; + var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) : + operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) : + operator === ">" || + operator === ">=" || + operator === "<" || + operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) : + operator === "in" ? + this._compileInOp(filter[1], filter.slice(2)) : + operator === "!in" ? + this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) : + operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") : + "true"; + return "(" + operation + ")"; + }; + FilterCreator.prototype._compare = function (a, b) { + return a < b ? -1 : a > b ? 1 : 0; + }; + FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) { + var left = this._compilePropertyReference(property); + var right = JSON.stringify(value); + return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right; + }; + FilterCreator.prototype._compileInOp = function (property, values) { + var compare = this._compare; + var left = JSON.stringify(values.sort(compare)); + var right = this._compilePropertyReference(property); + return left + ".indexOf(" + right + ")!==-1"; + }; + FilterCreator.prototype._compileLogicalOp = function (filters, operator) { + var compile = this._compile.bind(this); + return filters.map(compile).join(operator); + }; + FilterCreator.prototype._compileNegation = function (expression) { + return "!(" + expression + ")"; + }; + FilterCreator.prototype._compilePropertyReference = function (property) { + return "node[" + JSON.stringify(property) + "]"; + }; + return FilterCreator; +}()); +exports.FilterCreator = FilterCreator; +exports.default = FilterCreator; + +},{}],396:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var rbush = require("rbush"); +var Observable_1 = require("rxjs/Observable"); +var Subject_1 = require("rxjs/Subject"); var Edge_1 = require("../Edge"); var Error_1 = require("../Error"); var Graph_1 = require("../Graph"); @@ -26806,7 +37647,7 @@ var Graph_1 = require("../Graph"); * * @classdesc Represents a graph of nodes with edges. */ -var Graph = (function () { +var Graph = /** @class */ (function () { /** * Create a new graph instance. * @@ -26814,24 +37655,40 @@ var Graph = (function () { * @param {rbush.RBush} [nodeIndex] - Node index for fast spatial retreival. * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations. * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations. + * @param {FilterCreator} [filterCreator] - Instance for filter creation. + * @param {IGraphConfiguration} [configuration] - Configuration struct. */ - function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator) { + function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) { this._apiV3 = apiV3; this._cachedNodes = {}; this._cachedNodeTiles = {}; + this._cachedSequenceNodes = {}; this._cachedSpatialEdges = {}; this._cachedTiles = {}; this._cachingFill$ = {}; this._cachingFull$ = {}; + this._cachingSequenceNodes$ = {}; this._cachingSequences$ = {}; this._cachingSpatialArea$ = {}; this._cachingTiles$ = {}; this._changed$ = new Subject_1.Subject(); this._defaultAlt = 2; this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator(); + this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator(); + this._filter = this._filterCreator.createFilter(undefined); this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator(); + this._configuration = configuration != null ? + configuration : + { + maxSequences: 50, + maxUnusedNodes: 100, + maxUnusedPreStoredNodes: 30, + maxUnusedTiles: 20, + }; this._nodes = {}; - this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lon", ".lat", ".lon", ".lat"]); + this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]); + this._nodeIndexTiles = {}; + this._nodeToTile = {}; this._preStored = {}; this._requiredNodeTiles = {}; this._requiredSpatialArea = {}; @@ -26852,6 +37709,92 @@ var Graph = (function () { enumerable: true, configurable: true }); + /** + * Caches the full node data for all images within a bounding + * box. + * + * @description The node assets are not cached. + * + * @param {ILatLon} sw - South west corner of bounding box. + * @param {ILatLon} ne - North east corner of bounding box. + * @returns {Observable} Observable emitting the full + * nodes in the bounding box. + */ + Graph.prototype.cacheBoundingBox$ = function (sw, ne) { + var _this = this; + var cacheTiles$ = this._graphCalculator.encodeHsFromBoundingBox(sw, ne) + .filter(function (h) { + return !(h in _this._cachedTiles); + }) + .map(function (h) { + return h in _this._cachingTiles$ ? + _this._cachingTiles$[h] : + _this._cacheTile$(h); + }); + if (cacheTiles$.length === 0) { + cacheTiles$.push(Observable_1.Observable.of(this)); + } + return Observable_1.Observable + .from(cacheTiles$) + .mergeAll() + .last() + .mergeMap(function (graph) { + var nodes = _this._nodeIndex + .search({ + maxX: ne.lat, + maxY: ne.lon, + minX: sw.lat, + minY: sw.lon, + }) + .map(function (item) { + return item.node; + }); + var fullNodes = []; + var coreNodes = []; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + if (node.full) { + fullNodes.push(node); + } + else { + coreNodes.push(node.key); + } + } + var coreNodeBatches = []; + var batchSize = 200; + while (coreNodes.length > 0) { + coreNodeBatches.push(coreNodes.splice(0, batchSize)); + } + var fullNodes$ = Observable_1.Observable.of(fullNodes); + var fillNodes$ = coreNodeBatches + .map(function (batch) { + return _this._apiV3.imageByKeyFill$(batch) + .map(function (imageByKeyFill) { + var filledNodes = []; + for (var fillKey in imageByKeyFill) { + if (!imageByKeyFill.hasOwnProperty(fillKey)) { + continue; + } + if (_this.hasNode(fillKey)) { + var node = _this.getNode(fillKey); + if (!node.full) { + _this._makeFull(node, imageByKeyFill[fillKey]); + } + filledNodes.push(node); + } + } + return filledNodes; + }); + }); + return Observable_1.Observable + .merge(fullNodes$, Observable_1.Observable + .from(fillNodes$) + .mergeAll()); + }) + .reduce(function (acc, value) { + return acc.concat(value); + }); + }; /** * Retrieve and cache node fill properties. * @@ -26923,8 +37866,8 @@ var Graph = (function () { } } else { - if (fn.sequence == null || fn.sequence.key == null) { - throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ")."); + if (fn.sequence_key == null) { + throw new Error_1.GraphMapillaryError("Node has no sequence key (" + key + ")."); } var node = new Graph_1.Node(fn); _this._makeFull(node, fn); @@ -26993,10 +37936,89 @@ var Graph = (function () { if (!(node.sequenceKey in this._sequences)) { throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")"); } - var sequence = this._sequences[node.sequenceKey]; + var sequence = this._sequences[node.sequenceKey].sequence; var edges = this._edgeCalculator.computeSequenceEdges(node, sequence); node.cacheSequenceEdges(edges); }; + /** + * Retrieve and cache full nodes for all keys in a sequence. + * + * @param {string} sequenceKey - Key of sequence. + * @param {string} referenceNodeKey - Key of node to use as reference + * for optimized caching. + * @returns {Observable} Observable emitting the graph + * when the nodes of the sequence has been cached. + */ + Graph.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) { + var _this = this; + if (!this.hasSequence(sequenceKey)) { + throw new Error_1.GraphMapillaryError("Cannot cache sequence nodes of sequence that does not exist in graph (" + sequenceKey + ")."); + } + if (this.hasSequenceNodes(sequenceKey)) { + throw new Error_1.GraphMapillaryError("Sequence nodes already cached (" + sequenceKey + ")."); + } + var sequence = this.getSequence(sequenceKey); + if (sequence.key in this._cachingSequenceNodes$) { + return this._cachingSequenceNodes$[sequence.key]; + } + var batches = []; + var keys = sequence.keys.slice(); + var referenceBatchSize = 50; + if (!!referenceNodeKey && keys.length > referenceBatchSize) { + var referenceIndex = keys.indexOf(referenceNodeKey); + var startIndex = Math.max(0, Math.min(referenceIndex - referenceBatchSize / 2, keys.length - referenceBatchSize)); + batches.push(keys.splice(startIndex, referenceBatchSize)); + } + var batchSize = 200; + while (keys.length > 0) { + batches.push(keys.splice(0, batchSize)); + } + var batchesToCache = batches.length; + var sequenceNodes$ = Observable_1.Observable + .from(batches) + .mergeMap(function (batch) { + return _this._apiV3.imageByKeyFull$(batch) + .do(function (imageByKeyFull) { + for (var fullKey in imageByKeyFull) { + if (!imageByKeyFull.hasOwnProperty(fullKey)) { + continue; + } + var fn = imageByKeyFull[fullKey]; + if (_this.hasNode(fullKey)) { + var node = _this.getNode(fn.key); + if (!node.full) { + _this._makeFull(node, fn); + } + } + else { + if (fn.sequence_key == null) { + console.warn("Sequence missing, discarding node (" + fn.key + ")"); + } + var node = new Graph_1.Node(fn); + _this._makeFull(node, fn); + var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision); + _this._preStore(h, node); + _this._setNode(node); + } + } + batchesToCache--; + }) + .map(function (imageByKeyFull) { + return _this; + }); + }, 6) + .last() + .finally(function () { + delete _this._cachingSequenceNodes$[sequence.key]; + if (batchesToCache === 0) { + _this._cachedSequenceNodes[sequence.key] = true; + } + }) + .publish() + .refCount(); + this._cachingSequenceNodes$[sequence.key] = sequenceNodes$; + return sequenceNodes$; + }; /** * Retrieve and cache full nodes for a node spatial area. * @@ -27030,7 +38052,7 @@ var Graph = (function () { } var batchesToCache = batches.length; var spatialNodes$ = []; - var _loop_1 = function(batch) { + var _loop_1 = function (batch) { var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch) .do(function (imageByKeyFill) { for (var fillKey in imageByKeyFill) { @@ -27097,17 +38119,27 @@ var Graph = (function () { throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ")."); } var node = this.getNode(key); - var sequence = this._sequences[node.sequenceKey]; + var sequence = this._sequences[node.sequenceKey].sequence; var fallbackKeys = []; - var nextKey = sequence.findNextKey(node.key); var prevKey = sequence.findPrevKey(node.key); + if (prevKey != null) { + fallbackKeys.push(prevKey); + } + var nextKey = sequence.findNextKey(node.key); + if (nextKey != null) { + fallbackKeys.push(nextKey); + } var allSpatialNodes = this._requiredSpatialArea[key].all; var potentialNodes = []; + var filter = this._filter; for (var spatialNodeKey in allSpatialNodes) { if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) { continue; } - potentialNodes.push(allSpatialNodes[spatialNodeKey]); + var spatialNode = allSpatialNodes[spatialNodeKey]; + if (filter(spatialNode)) { + potentialNodes.push(spatialNode); + } } var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys); var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey); @@ -27118,13 +38150,14 @@ var Graph = (function () { node.cacheSpatialEdges(edges); this._cachedSpatialEdges[key] = node; delete this._requiredSpatialArea[key]; + delete this._cachedNodeTiles[key]; }; /** * Retrieve and cache geohash tiles for a node. * * @param {string} key - Key of node for which to retrieve tiles. - * @returns {Observable} Observable emitting the graph - * when the tiles required for the node has been cached. + * @returns {Array>} Array of observables emitting + * the graph for each tile required for the node has been cached. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ @@ -27133,6 +38166,9 @@ var Graph = (function () { if (key in this._cachedNodeTiles) { throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ")."); } + if (key in this._cachedSpatialEdges) { + throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ")."); + } if (!(key in this._requiredNodeTiles)) { throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ")."); } @@ -27148,59 +38184,10 @@ var Graph = (function () { nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs); nodeTiles.cache = []; var cacheTiles$ = []; - var _loop_2 = function(h) { - var cacheTile$ = null; - if (h in this_2._cachingTiles$) { - cacheTile$ = this_2._cachingTiles$[h]; - } - else { - cacheTile$ = this_2._apiV3.imagesByH$([h]) - .do(function (imagesByH) { - var coreNodes = imagesByH[h]; - if (h in _this._cachedTiles) { - return; - } - _this._cachedTiles[h] = []; - var hCache = _this._cachedTiles[h]; - var preStored = _this._removeFromPreStore(h); - for (var index in coreNodes) { - if (!coreNodes.hasOwnProperty(index)) { - continue; - } - var coreNode = coreNodes[index]; - if (coreNode == null) { - break; - } - if (coreNode.sequence == null || - coreNode.sequence.key == null) { - console.warn("Sequence missing, discarding (" + coreNode.key + ")"); - continue; - } - if (preStored != null && coreNode.key in preStored) { - var node_1 = preStored[coreNode.key]; - delete preStored[coreNode.key]; - hCache.push(node_1); - _this._nodeIndex.insert({ lat: node_1.latLon.lat, lon: node_1.latLon.lon, node: node_1 }); - continue; - } - var node = new Graph_1.Node(coreNode); - hCache.push(node); - _this._nodeIndex.insert({ lat: node.latLon.lat, lon: node.latLon.lon, node: node }); - _this._setNode(node); - } - delete _this._cachingTiles$[h]; - }) - .map(function (imagesByH) { - return _this; - }) - .catch(function (error) { - delete _this._cachingTiles$[h]; - throw error; - }) - .publish() - .refCount(); - this_2._cachingTiles$[h] = cacheTile$; - } + var _loop_2 = function (h) { + var cacheTile$ = h in this_2._cachingTiles$ ? + this_2._cachingTiles$[h] : + this_2._cacheTile$(h); cacheTiles$.push(cacheTile$ .do(function (graph) { var index = nodeTiles.caching.indexOf(h); @@ -27251,7 +38238,9 @@ var Graph = (function () { } var node = this.getNode(key); node.initializeCache(new Graph_1.NodeCache()); - this._cachedNodes[key] = node; + var accessed = new Date().getTime(); + this._cachedNodes[key] = { accessed: accessed, node: node }; + this._updateCachedTileAccess(key, accessed); }; /** * Get a value indicating if the graph is fill caching a node. @@ -27289,8 +38278,18 @@ var Graph = (function () { * @returns {boolean} Value indicating if the sequence is * being cached. */ - Graph.prototype.isCachingSequence = function (sequenceKey) { - return sequenceKey in this._cachingSequences$; + Graph.prototype.isCachingSequence = function (sequenceKey) { + return sequenceKey in this._cachingSequences$; + }; + /** + * Get a value indicating if the graph is caching sequence nodes. + * + * @param {string} sequenceKey - Key of sequence. + * @returns {boolean} Value indicating if the sequence nodes are + * being cached. + */ + Graph.prototype.isCachingSequenceNodes = function (sequenceKey) { + return sequenceKey in this._cachingSequenceNodes$; }; /** * Get a value indicating if the graph is caching the tiles @@ -27323,6 +38322,9 @@ var Graph = (function () { * @returns {boolean} Value indicating if a node exist in the graph. */ Graph.prototype.hasNode = function (key) { + var accessed = new Date().getTime(); + this._updateCachedNodeAccess(key, accessed); + this._updateCachedTileAccess(key, accessed); return key in this._nodes; }; /** @@ -27334,7 +38336,12 @@ var Graph = (function () { */ Graph.prototype.hasNodeSequence = function (key) { var node = this.getNode(key); - return node.sequenceKey in this._sequences; + var sequenceKey = node.sequenceKey; + var hasNodeSequence = sequenceKey in this._sequences; + if (hasNodeSequence) { + this._sequences[sequenceKey].accessed = new Date().getTime(); + } + return hasNodeSequence; }; /** * Get a value indicating if a sequence exist in the graph. @@ -27344,7 +38351,21 @@ var Graph = (function () { * in the graph. */ Graph.prototype.hasSequence = function (sequenceKey) { - return sequenceKey in this._sequences; + var hasSequence = sequenceKey in this._sequences; + if (hasSequence) { + this._sequences[sequenceKey].accessed = new Date().getTime(); + } + return hasSequence; + }; + /** + * Get a value indicating if sequence nodes has been cached in the graph. + * + * @param {string} sequenceKey - Key of sequence. + * @returns {boolean} Value indicating if a sequence nodes has been + * cached in the graph. + */ + Graph.prototype.hasSequenceNodes = function (sequenceKey) { + return sequenceKey in this._cachedSequenceNodes; }; /** * Get a value indicating if the graph has fully cached @@ -27367,10 +38388,10 @@ var Graph = (function () { var node = this.getNode(key); var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold); var spatialItems = this._nodeIndex.search({ - maxX: bbox[1].lon, - maxY: bbox[1].lat, - minX: bbox[0].lon, - minY: bbox[0].lat, + maxX: bbox[1].lat, + maxY: bbox[1].lon, + minX: bbox[0].lat, + minY: bbox[0].lon, }); var spatialNodes = { all: {}, @@ -27401,23 +38422,28 @@ var Graph = (function () { if (key in this._cachedNodeTiles) { return true; } + if (key in this._cachedSpatialEdges) { + return true; + } if (!this.hasNode(key)) { throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ")."); } + var nodeTiles = { cache: [], caching: [] }; if (!(key in this._requiredNodeTiles)) { var node = this.getNode(key); - var cache = this._graphCalculator + nodeTiles.cache = this._graphCalculator .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold) .filter(function (h) { return !(h in _this._cachedTiles); }); - this._requiredNodeTiles[key] = { - cache: cache, - caching: [], - }; + if (nodeTiles.cache.length > 0) { + this._requiredNodeTiles[key] = nodeTiles; + } + } + else { + nodeTiles = this._requiredNodeTiles[key]; } - return this._requiredNodeTiles[key].cache.length === 0 && - this._requiredNodeTiles[key].caching.length === 0; + return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0; }; /** * Get a node. @@ -27426,6 +38452,9 @@ var Graph = (function () { * @returns {Node} Retrieved node. */ Graph.prototype.getNode = function (key) { + var accessed = new Date().getTime(); + this._updateCachedNodeAccess(key, accessed); + this._updateCachedTileAccess(key, accessed); return this._nodes[key]; }; /** @@ -27435,25 +38464,238 @@ var Graph = (function () { * @returns {Node} Retrieved sequence. */ Graph.prototype.getSequence = function (sequenceKey) { - return this._sequences[sequenceKey]; + var sequenceAccess = this._sequences[sequenceKey]; + sequenceAccess.accessed = new Date().getTime(); + return sequenceAccess.sequence; }; /** * Reset all spatial edges of the graph nodes. */ - Graph.prototype.reset = function () { - var spatialNodeKeys = Object.keys(this._requiredSpatialArea); - for (var _i = 0, spatialNodeKeys_1 = spatialNodeKeys; _i < spatialNodeKeys_1.length; _i++) { - var spatialNodeKey = spatialNodeKeys_1[_i]; - delete this._requiredSpatialArea[spatialNodeKey]; - } + Graph.prototype.resetSpatialEdges = function () { var cachedKeys = Object.keys(this._cachedSpatialEdges); - for (var _a = 0, cachedKeys_1 = cachedKeys; _a < cachedKeys_1.length; _a++) { - var cachedKey = cachedKeys_1[_a]; + for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) { + var cachedKey = cachedKeys_1[_i]; var node = this._cachedSpatialEdges[cachedKey]; node.resetSpatialEdges(); delete this._cachedSpatialEdges[cachedKey]; } }; + /** + * Reset the complete graph but keep the nodes corresponding + * to the supplied keys. All other nodes will be disposed. + * + * @param {Array} keepKeys - Keys for nodes to keep + * in graph after reset. + */ + Graph.prototype.reset = function (keepKeys) { + var nodes = []; + for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) { + var key = keepKeys_1[_i]; + if (!this.hasNode(key)) { + throw new Error("Node does not exist " + key); + } + var node = this.getNode(key); + node.resetSequenceEdges(); + node.resetSpatialEdges(); + nodes.push(node); + } + for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) { + var cachedKey = _b[_a]; + if (keepKeys.indexOf(cachedKey) !== -1) { + continue; + } + this._cachedNodes[cachedKey].node.dispose(); + delete this._cachedNodes[cachedKey]; + } + this._cachedNodeTiles = {}; + this._cachedSpatialEdges = {}; + this._cachedTiles = {}; + this._cachingFill$ = {}; + this._cachingFull$ = {}; + this._cachingSequences$ = {}; + this._cachingSpatialArea$ = {}; + this._cachingTiles$ = {}; + this._nodes = {}; + this._nodeToTile = {}; + this._preStored = {}; + for (var _c = 0, nodes_2 = nodes; _c < nodes_2.length; _c++) { + var node = nodes_2[_c]; + this._nodes[node.key] = node; + var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision); + this._preStore(h, node); + } + this._requiredNodeTiles = {}; + this._requiredSpatialArea = {}; + this._sequences = {}; + this._nodeIndexTiles = {}; + this._nodeIndex.clear(); + }; + /** + * Set the spatial node filter. + * + * @param {FilterExpression} filter - Filter expression to be applied + * when calculating spatial edges. + */ + Graph.prototype.setFilter = function (filter) { + this._filter = this._filterCreator.createFilter(filter); + }; + /** + * Uncache the graph according to the graph configuration. + * + * @description Uncaches unused tiles, unused nodes and + * sequences according to the numbers specified in the + * graph configuration. Sequences does not have a direct + * reference to either tiles or nodes and may be uncached + * even if they are related to the nodes that should be kept. + * + * @param {Array} keepKeys - Keys of nodes to keep in + * graph unrelated to last access. Tiles related to those keys + * will also be kept in graph. + * @param {string} keepSequenceKey - Optional key of sequence + * for which the belonging nodes should not be disposed or + * removed from the graph. These nodes may still be uncached if + * not specified in keep keys param. + */ + Graph.prototype.uncache = function (keepKeys, keepSequenceKey) { + var keysInUse = {}; + this._addNewKeys(keysInUse, this._cachingFull$); + this._addNewKeys(keysInUse, this._cachingFill$); + this._addNewKeys(keysInUse, this._cachingSpatialArea$); + this._addNewKeys(keysInUse, this._requiredNodeTiles); + this._addNewKeys(keysInUse, this._requiredSpatialArea); + for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) { + var key = keepKeys_2[_i]; + if (key in keysInUse) { + continue; + } + keysInUse[key] = true; + } + var keepHs = {}; + for (var key in keysInUse) { + if (!keysInUse.hasOwnProperty(key)) { + continue; + } + var node = this._nodes[key]; + var nodeHs = this._graphCalculator.encodeHs(node.latLon); + for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) { + var nodeH = nodeHs_1[_a]; + if (!(nodeH in keepHs)) { + keepHs[nodeH] = true; + } + } + } + var potentialHs = []; + for (var h in this._cachedTiles) { + if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) { + continue; + } + potentialHs.push([h, this._cachedTiles[h]]); + } + var uncacheHs = potentialHs + .sort(function (h1, h2) { + return h2[1].accessed - h1[1].accessed; + }) + .slice(this._configuration.maxUnusedTiles) + .map(function (h) { + return h[0]; + }); + for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) { + var uncacheH = uncacheHs_1[_b]; + this._uncacheTile(uncacheH, keepSequenceKey); + } + var potentialPreStored = []; + var nonCachedPreStored = []; + for (var h in this._preStored) { + if (!this._preStored.hasOwnProperty(h) || h in this._cachingTiles$) { + continue; + } + var prestoredNodes = this._preStored[h]; + for (var key in prestoredNodes) { + if (!prestoredNodes.hasOwnProperty(key) || key in keysInUse) { + continue; + } + if (prestoredNodes[key].sequenceKey === keepSequenceKey) { + continue; + } + if (key in this._cachedNodes) { + potentialPreStored.push([this._cachedNodes[key], h]); + } + else { + nonCachedPreStored.push([key, h]); + } + } + } + var uncachePreStored = potentialPreStored + .sort(function (_a, _b) { + var na1 = _a[0], h1 = _a[1]; + var na2 = _b[0], h2 = _b[1]; + return na2.accessed - na1.accessed; + }) + .slice(this._configuration.maxUnusedPreStoredNodes) + .map(function (_a) { + var na = _a[0], h = _a[1]; + return [na.node.key, h]; + }); + this._uncachePreStored(nonCachedPreStored); + this._uncachePreStored(uncachePreStored); + var potentialNodes = []; + for (var key in this._cachedNodes) { + if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) { + continue; + } + potentialNodes.push(this._cachedNodes[key]); + } + var uncacheNodes = potentialNodes + .sort(function (n1, n2) { + return n2.accessed - n1.accessed; + }) + .slice(this._configuration.maxUnusedNodes); + for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) { + var nodeAccess = uncacheNodes_1[_c]; + nodeAccess.node.uncache(); + var key = nodeAccess.node.key; + delete this._cachedNodes[key]; + if (key in this._cachedNodeTiles) { + delete this._cachedNodeTiles[key]; + } + if (key in this._cachedSpatialEdges) { + delete this._cachedSpatialEdges[key]; + } + } + var potentialSequences = []; + for (var sequenceKey in this._sequences) { + if (!this._sequences.hasOwnProperty(sequenceKey) || + sequenceKey in this._cachingSequences$ || + sequenceKey === keepSequenceKey) { + continue; + } + potentialSequences.push(this._sequences[sequenceKey]); + } + var uncacheSequences = potentialSequences + .sort(function (s1, s2) { + return s2.accessed - s1.accessed; + }) + .slice(this._configuration.maxSequences); + for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) { + var sequenceAccess = uncacheSequences_1[_d]; + var sequenceKey = sequenceAccess.sequence.key; + delete this._sequences[sequenceKey]; + if (sequenceKey in this._cachedSequenceNodes) { + delete this._cachedSequenceNodes[sequenceKey]; + } + sequenceAccess.sequence.dispose(); + } + }; + Graph.prototype._addNewKeys = function (keys, dict) { + for (var key in dict) { + if (!dict.hasOwnProperty(key) || !this.hasNode(key)) { + continue; + } + if (!(key in keys)) { + keys[key] = true; + } + } + }; Graph.prototype._cacheSequence$ = function (sequenceKey) { var _this = this; if (sequenceKey in this._cachingSequences$) { @@ -27462,7 +38704,10 @@ var Graph = (function () { this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey]) .do(function (sequenceByKey) { if (!(sequenceKey in _this._sequences)) { - _this._sequences[sequenceKey] = new Graph_1.Sequence(sequenceByKey[sequenceKey]); + _this._sequences[sequenceKey] = { + accessed: new Date().getTime(), + sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]), + }; } delete _this._cachingSequences$[sequenceKey]; }) @@ -27479,6 +38724,69 @@ var Graph = (function () { .refCount(); return this._cachingSequences$[sequenceKey]; }; + Graph.prototype._cacheTile$ = function (h) { + var _this = this; + this._cachingTiles$[h] = this._apiV3.imagesByH$([h]) + .do(function (imagesByH) { + var coreNodes = imagesByH[h]; + if (h in _this._cachedTiles) { + return; + } + _this._nodeIndexTiles[h] = []; + _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] }; + var hCache = _this._cachedTiles[h].nodes; + var preStored = _this._removeFromPreStore(h); + for (var index in coreNodes) { + if (!coreNodes.hasOwnProperty(index)) { + continue; + } + var coreNode = coreNodes[index]; + if (coreNode == null) { + break; + } + if (coreNode.sequence_key == null) { + console.warn("Sequence missing, discarding node (" + coreNode.key + ")"); + continue; + } + if (preStored != null && coreNode.key in preStored) { + var preStoredNode = preStored[coreNode.key]; + delete preStored[coreNode.key]; + hCache.push(preStoredNode); + var preStoredNodeIndexItem = { + lat: preStoredNode.latLon.lat, + lon: preStoredNode.latLon.lon, + node: preStoredNode, + }; + _this._nodeIndex.insert(preStoredNodeIndexItem); + _this._nodeIndexTiles[h].push(preStoredNodeIndexItem); + _this._nodeToTile[preStoredNode.key] = h; + continue; + } + var node = new Graph_1.Node(coreNode); + hCache.push(node); + var nodeIndexItem = { + lat: node.latLon.lat, + lon: node.latLon.lon, + node: node, + }; + _this._nodeIndex.insert(nodeIndexItem); + _this._nodeIndexTiles[h].push(nodeIndexItem); + _this._nodeToTile[node.key] = h; + _this._setNode(node); + } + delete _this._cachingTiles$[h]; + }) + .map(function (imagesByH) { + return _this; + }) + .catch(function (error) { + delete _this._cachingTiles$[h]; + throw error; + }) + .publish() + .refCount(); + return this._cachingTiles$[h]; + }; Graph.prototype._makeFull = function (node, fillNode) { if (fillNode.calt == null) { fillNode.calt = this._defaultAlt; @@ -27509,19 +38817,90 @@ var Graph = (function () { } this._nodes[key] = node; }; + Graph.prototype._uncacheTile = function (h, keepSequenceKey) { + for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) { + var node = _a[_i]; + var key = node.key; + delete this._nodeToTile[key]; + if (key in this._cachedNodes) { + delete this._cachedNodes[key]; + } + if (key in this._cachedNodeTiles) { + delete this._cachedNodeTiles[key]; + } + if (key in this._cachedSpatialEdges) { + delete this._cachedSpatialEdges[key]; + } + if (node.sequenceKey === keepSequenceKey) { + this._preStore(h, node); + node.uncache(); + } + else { + delete this._nodes[key]; + if (node.sequenceKey in this._cachedSequenceNodes) { + delete this._cachedSequenceNodes[node.sequenceKey]; + } + node.dispose(); + } + } + for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) { + var nodeIndexItem = _c[_b]; + this._nodeIndex.remove(nodeIndexItem); + } + delete this._nodeIndexTiles[h]; + delete this._cachedTiles[h]; + }; + Graph.prototype._uncachePreStored = function (preStored) { + var hs = {}; + for (var _i = 0, preStored_1 = preStored; _i < preStored_1.length; _i++) { + var _a = preStored_1[_i], key = _a[0], h = _a[1]; + if (key in this._nodes) { + delete this._nodes[key]; + } + if (key in this._cachedNodes) { + delete this._cachedNodes[key]; + } + var node = this._preStored[h][key]; + if (node.sequenceKey in this._cachedSequenceNodes) { + delete this._cachedSequenceNodes[node.sequenceKey]; + } + delete this._preStored[h][key]; + node.dispose(); + hs[h] = true; + } + for (var h in hs) { + if (!hs.hasOwnProperty(h)) { + continue; + } + if (Object.keys(this._preStored[h]).length === 0) { + delete this._preStored[h]; + } + } + }; + Graph.prototype._updateCachedTileAccess = function (key, accessed) { + if (key in this._nodeToTile) { + this._cachedTiles[this._nodeToTile[key]].accessed = accessed; + } + }; + Graph.prototype._updateCachedNodeAccess = function (key, accessed) { + if (key in this._cachedNodes) { + this._cachedNodes[key].accessed = accessed; + } + }; return Graph; }()); exports.Graph = Graph; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Graph; -},{"../Edge":208,"../Error":209,"../Graph":211,"rbush":24,"rxjs/Subject":33,"rxjs/add/observable/from":40,"rxjs/add/operator/catch":48,"rxjs/add/operator/do":54,"rxjs/add/operator/finally":57,"rxjs/add/operator/map":60,"rxjs/add/operator/publish":66}],281:[function(require,module,exports){ -/// +},{"../Edge":291,"../Error":292,"../Graph":294,"rbush":25,"rxjs/Observable":29,"rxjs/Subject":34}],397:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var geohash = require("latlon-geohash"); var THREE = require("three"); +var Error_1 = require("../Error"); var Geo_1 = require("../Geo"); -var GeoHashDirections = (function () { +var GeoHashDirections = /** @class */ (function () { function GeoHashDirections() { } GeoHashDirections.n = "n"; @@ -27534,14 +38913,42 @@ var GeoHashDirections = (function () { GeoHashDirections.ne = "ne"; return GeoHashDirections; }()); -var GraphCalculator = (function () { +/** + * @class GraphCalculator + * + * @classdesc Represents a calculator for graph entities. + */ +var GraphCalculator = /** @class */ (function () { + /** + * Create a new graph calculator instance. + * + * @param {GeoCoords} geoCoords - Geo coords instance. + */ function GraphCalculator(geoCoords) { this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords(); } + /** + * Encode the geohash tile for geodetic coordinates. + * + * @param {ILatLon} latlon - Latitude and longitude to encode. + * @param {number} precision - Precision of the encoding. + * + * @returns {string} The geohash tile for the lat, lon and precision. + */ GraphCalculator.prototype.encodeH = function (latLon, precision) { if (precision === void 0) { precision = 7; } return geohash.encode(latLon.lat, latLon.lon, precision); }; + /** + * Encode the geohash tiles within a threshold from a position + * using Manhattan distance. + * + * @param {ILatLon} latlon - Latitude and longitude to encode. + * @param {number} precision - Precision of the encoding. + * @param {number} threshold - Threshold of the encoding in meters. + * + * @returns {string} The geohash tiles reachable within the threshold. + */ GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) { if (precision === void 0) { precision = 7; } if (threshold === void 0) { threshold = 20; } @@ -27588,6 +38995,42 @@ var GraphCalculator = (function () { } return hs; }; + /** + * Encode the minimum set of geohash tiles containing a bounding box. + * + * @description The current algorithm does expect the bounding box + * to be sufficiently small to be contained in an area with the size + * of maximally four tiles. Up to nine adjacent tiles may be returned. + * The method currently uses the largest side as the threshold leading to + * more tiles being returned than needed in edge cases. + * + * @param {ILatLon} sw - South west corner of bounding box. + * @param {ILatLon} ne - North east corner of bounding box. + * @param {number} precision - Precision of the encoding. + * + * @returns {string} The geohash tiles containing the bounding box. + */ + GraphCalculator.prototype.encodeHsFromBoundingBox = function (sw, ne, precision) { + if (precision === void 0) { precision = 7; } + if (ne.lat <= sw.lat || ne.lon <= sw.lon) { + throw new Error_1.GraphMapillaryError("North east needs to be top right of south west"); + } + var centerLat = (sw.lat + ne.lat) / 2; + var centerLon = (sw.lon + ne.lon) / 2; + var enu = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, centerLat, centerLon, 0); + var threshold = Math.max(enu[0], enu[1]); + return this.encodeHs({ lat: centerLat, lon: centerLon }, precision, threshold); + }; + /** + * Get the bounding box corners for a circle with radius of a threshold + * with center in a geodetic position. + * + * @param {ILatLon} latlon - Latitude and longitude to encode. + * @param {number} threshold - Threshold distance from the position in meters. + * + * @returns {Array} The south west and north east corners of the + * bounding box. + */ GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) { var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0); var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0); @@ -27596,6 +39039,14 @@ var GraphCalculator = (function () { { lat: tr[0], lon: tr[1] }, ]; }; + /** + * Convert a compass angle to an angle axis rotation vector. + * + * @param {number} compassAngle - The compass angle in degrees. + * @param {number} orientation - The orientation of the original image. + * + * @returns {Array} Angle axis rotation vector. + */ GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) { var x = 0; var y = 0; @@ -27628,28 +39079,52 @@ var GraphCalculator = (function () { return GraphCalculator; }()); exports.GraphCalculator = GraphCalculator; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = GraphCalculator; -},{"../Geo":210,"latlon-geohash":20,"three":157}],282:[function(require,module,exports){ +},{"../Error":292,"../Geo":293,"latlon-geohash":21,"three":240}],398:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Enumeration for graph modes. + * @enum {number} + * @readonly + * @description Modes for the retrieval and caching performed + * by the graph service on the graph. + */ +var GraphMode; +(function (GraphMode) { + /** + * Caching is performed on sequences only and sequence edges are + * calculated. Spatial tiles + * are not retrieved and spatial edges are not calculated when + * caching nodes. Complete sequences are being cached for requested + * nodes within the graph. + */ + GraphMode[GraphMode["Sequence"] = 0] = "Sequence"; + /** + * Caching is performed with emphasis on spatial data. Sequence edges + * as well as spatial edges are cached. Sequence data + * is still requested but complete sequences are not being cached + * for requested nodes. + * + * This is the initial mode of the graph service. + */ + GraphMode[GraphMode["Spatial"] = 1] = "Spatial"; +})(GraphMode = exports.GraphMode || (exports.GraphMode = {})); +exports.default = GraphMode; + +},{}],399:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/operator/catch"); -require("rxjs/add/operator/concat"); -require("rxjs/add/operator/do"); -require("rxjs/add/operator/expand"); -require("rxjs/add/operator/finally"); -require("rxjs/add/operator/first"); -require("rxjs/add/operator/last"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/mergeMap"); -require("rxjs/add/operator/publishReplay"); +var Subject_1 = require("rxjs/Subject"); +var Graph_1 = require("../Graph"); /** * @class GraphService * * @classdesc Represents a service for graph operations. */ -var GraphService = (function () { +var GraphService = /** @class */ (function () { /** * Create a new graph service instance. * @@ -27661,10 +39136,57 @@ var GraphService = (function () { .concat(graph.changed$) .publishReplay(1) .refCount(); - this._graph$.subscribe(); + this._graph$.subscribe(function () { }); + this._graphMode = Graph_1.GraphMode.Spatial; + this._graphModeSubject$ = new Subject_1.Subject(); + this._graphMode$ = this._graphModeSubject$ + .startWith(this._graphMode) + .publishReplay(1) + .refCount(); + this._graphMode$.subscribe(function () { }); this._imageLoadingService = imageLoadingService; + this._firstGraphSubjects$ = []; + this._initializeCacheSubscriptions = []; + this._sequenceSubscriptions = []; this._spatialSubscriptions = []; } + Object.defineProperty(GraphService.prototype, "graphMode$", { + /** + * Get graph mode observable. + * + * @description Emits the current graph mode. + * + * @returns {Observable} Observable + * emitting the current graph mode when it changes. + */ + get: function () { + return this._graphMode$; + }, + enumerable: true, + configurable: true + }); + /** + * Cache full nodes in a bounding box. + * + * @description When called, the full properties of + * the node are retrieved. The node cache is not initialized + * for any new nodes retrieved and the node assets are not + * retrieved, {@link cacheNode$} needs to be called for caching + * assets. + * + * @param {ILatLon} sw - South west corner of bounding box. + * @param {ILatLon} ne - North east corner of bounding box. + * @return {Observable>} Observable emitting a single item, + * the nodes of the bounding box, when they have all been retrieved. + * @throws {Error} Propagates any IO node caching errors to the caller. + */ + GraphService.prototype.cacheBoundingBox$ = function (sw, ne) { + return this._graph$ + .first() + .mergeMap(function (graph) { + return graph.cacheBoundingBox$(sw, ne); + }); + }; /** * Cache a node in the graph and retrieve it. * @@ -27685,7 +39207,28 @@ var GraphService = (function () { */ GraphService.prototype.cacheNode$ = function (key) { var _this = this; - var firstGraph$ = this._graph$ + var firstGraphSubject$ = new Subject_1.Subject(); + this._firstGraphSubjects$.push(firstGraphSubject$); + var firstGraph$ = firstGraphSubject$ + .publishReplay(1) + .refCount(); + var node$ = firstGraph$ + .map(function (graph) { + return graph.getNode(key); + }) + .mergeMap(function (node) { + return node.assetsCached ? + Observable_1.Observable.of(node) : + node.cacheAssets$(); + }) + .publishReplay(1) + .refCount(); + node$.subscribe(function (node) { + _this._imageLoadingService.loadnode$.next(node); + }, function (error) { + console.error("Failed to cache node (" + key + ")", error); + }); + var initializeCacheSubscription = this._graph$ .first() .mergeMap(function (graph) { if (graph.isCachingFull(key) || !graph.hasNode(key)) { @@ -27699,99 +39242,111 @@ var GraphService = (function () { .do(function (graph) { if (!graph.hasInitializedCache(key)) { graph.initializeCache(key); - } - }) - .publishReplay(1) - .refCount(); - var node$ = firstGraph$ - .map(function (graph) { - return graph.getNode(key); - }) - .mergeMap(function (node) { - return node.assetsCached ? - Observable_1.Observable.of(node) : - node.cacheAssets$(); + } }) - .publishReplay(1) - .refCount(); - node$.subscribe(function (node) { - _this._imageLoadingService.loadnode$.next(node); + .finally(function () { + if (initializeCacheSubscription == null) { + return; + } + _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions); + _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$); + }) + .subscribe(function (graph) { + firstGraphSubject$.next(graph); + firstGraphSubject$.complete(); }, function (error) { - console.error("Failed to cache node (" + key + ")", error); + firstGraphSubject$.error(error); }); - firstGraph$ + if (!initializeCacheSubscription.closed) { + this._initializeCacheSubscriptions.push(initializeCacheSubscription); + } + var graphSequence$ = firstGraph$ .mergeMap(function (graph) { if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) { return graph.cacheNodeSequence$(key); } return Observable_1.Observable.of(graph); }) + .publishReplay(1) + .refCount(); + var sequenceSubscription = graphSequence$ .do(function (graph) { if (!graph.getNode(key).sequenceEdges.cached) { graph.cacheSequenceEdges(key); } + }) + .finally(function () { + if (sequenceSubscription == null) { + return; + } + _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions); }) .subscribe(function (graph) { return; }, function (error) { console.error("Failed to cache sequence edges (" + key + ").", error); }); - var spatialSubscription = firstGraph$ - .expand(function (graph) { - if (graph.hasTiles(key)) { - return Observable_1.Observable.empty(); - } - return Observable_1.Observable - .from(graph.cacheTiles$(key)) - .mergeMap(function (graph$) { - return graph$ - .mergeMap(function (g) { - if (g.isCachingTiles(key)) { - return Observable_1.Observable.empty(); - } - return Observable_1.Observable.of(g); - }) - .catch(function (error, caught$) { - console.error("Failed to cache tile data (" + key + ").", error); + if (!sequenceSubscription.closed) { + this._sequenceSubscriptions.push(sequenceSubscription); + } + if (this._graphMode === Graph_1.GraphMode.Spatial) { + var spatialSubscription_1 = firstGraph$ + .expand(function (graph) { + if (graph.hasTiles(key)) { return Observable_1.Observable.empty(); + } + return Observable_1.Observable + .from(graph.cacheTiles$(key)) + .mergeMap(function (graph$) { + return graph$ + .mergeMap(function (g) { + if (g.isCachingTiles(key)) { + return Observable_1.Observable.empty(); + } + return Observable_1.Observable.of(g); + }) + .catch(function (error, caught$) { + console.error("Failed to cache tile data (" + key + ").", error); + return Observable_1.Observable.empty(); + }); }); - }); - }) - .last() - .mergeMap(function (graph) { - if (graph.hasSpatialArea(key)) { - return Observable_1.Observable.of(graph); - } - return Observable_1.Observable - .from(graph.cacheSpatialArea$(key)) - .mergeMap(function (graph$) { - return graph$ - .catch(function (error, caught$) { - console.error("Failed to cache spatial nodes (" + key + ").", error); - return Observable_1.Observable.empty(); + }) + .last() + .mergeMap(function (graph) { + if (graph.hasSpatialArea(key)) { + return Observable_1.Observable.of(graph); + } + return Observable_1.Observable + .from(graph.cacheSpatialArea$(key)) + .mergeMap(function (graph$) { + return graph$ + .catch(function (error, caught$) { + console.error("Failed to cache spatial nodes (" + key + ").", error); + return Observable_1.Observable.empty(); + }); }); + }) + .last() + .mergeMap(function (graph) { + return graph.hasNodeSequence(key) ? + Observable_1.Observable.of(graph) : + graph.cacheNodeSequence$(key); + }) + .do(function (graph) { + if (!graph.getNode(key).spatialEdges.cached) { + graph.cacheSpatialEdges(key); + } + }) + .finally(function () { + if (spatialSubscription_1 == null) { + return; + } + _this._removeFromArray(spatialSubscription_1, _this._spatialSubscriptions); + }) + .subscribe(function (graph) { return; }, function (error) { + console.error("Failed to cache spatial edges (" + key + ").", error); }); - }) - .last() - .mergeMap(function (graph) { - return graph.hasNodeSequence(key) ? - Observable_1.Observable.of(graph) : - graph.cacheNodeSequence$(key); - }) - .do(function (graph) { - if (!graph.getNode(key).spatialEdges.cached) { - graph.cacheSpatialEdges(key); - } - }) - .finally(function () { - if (spatialSubscription == null) { - return; + if (!spatialSubscription_1.closed) { + this._spatialSubscriptions.push(spatialSubscription_1); } - _this._removeSpatialSubscription(spatialSubscription); - }) - .subscribe(function (graph) { return; }, function (error) { - console.error("Failed to cache spatial edges (" + key + ").", error); - }); - if (!spatialSubscription.closed) { - this._spatialSubscriptions.push(spatialSubscription); } return node$ .first(function (node) { @@ -27820,113 +39375,194 @@ var GraphService = (function () { }); }; /** - * Reset the spatial edges of all cached nodes and recaches the - * spatial edges of the provided node. + * Cache a sequence and its nodes in the graph and retrieve the sequence. * - * @param {string} key - Key of the node to cache edges for after reset. + * @description Caches a sequence and its assets are cached and + * retrieves all nodes belonging to the sequence. The node assets + * or edges will not be cached. + * + * @param {string} sequenceKey - Sequence key. + * @param {string} referenceNodeKey - Key of node to use as reference + * for optimized caching. * @returns {Observable} Observable emitting a single item, - * the node, when it has been retrieved and its assets are cached after - * the spatial reset. + * the sequence, when it has been retrieved, its assets are cached and + * all nodes belonging to the sequence has been retrieved. * @throws {Error} Propagates any IO node caching errors to the caller. */ - GraphService.prototype.reset$ = function (key) { - var _this = this; - this._resetSpatialSubscriptions(); + GraphService.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) { return this._graph$ .first() - .do(function (graph) { - graph.reset(); + .mergeMap(function (graph) { + if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) { + return graph.cacheSequence$(sequenceKey); + } + return Observable_1.Observable.of(graph); }) .mergeMap(function (graph) { - return _this.cacheNode$(key); + if (graph.isCachingSequenceNodes(sequenceKey) || !graph.hasSequenceNodes(sequenceKey)) { + return graph.cacheSequenceNodes$(sequenceKey, referenceNodeKey); + } + return Observable_1.Observable.of(graph); + }) + .map(function (graph) { + return graph.getSequence(sequenceKey); + }); + }; + /** + * Set a spatial edge filter on the graph. + * + * @description Resets the spatial edges of all cached nodes. + * + * @param {FilterExpression} filter - Filter expression to be applied. + * @return {Observable} Observable emitting a single item, + * the graph, when the spatial edges have been reset. + */ + GraphService.prototype.setFilter$ = function (filter) { + this._resetSubscriptions(this._spatialSubscriptions); + return this._graph$ + .first() + .do(function (graph) { + graph.resetSpatialEdges(); + graph.setFilter(filter); + }) + .map(function (graph) { + return undefined; + }); + }; + /** + * Set the graph mode. + * + * @description If graph mode is set to spatial, caching + * is performed with emphasis on spatial edges. If graph + * mode is set to sequence no tile data is requested and + * no spatial edges are computed. + * + * When setting graph mode to sequence all spatial + * subscriptions are aborted. + * + * @param {GraphMode} mode - Graph mode to set. + */ + GraphService.prototype.setGraphMode = function (mode) { + if (this._graphMode === mode) { + return; + } + if (mode === Graph_1.GraphMode.Sequence) { + this._resetSubscriptions(this._spatialSubscriptions); + } + this._graphMode = mode; + this._graphModeSubject$.next(this._graphMode); + }; + /** + * Reset the graph. + * + * @description Resets the graph but keeps the nodes of the + * supplied keys. + * + * @param {Array} keepKeys - Keys of nodes to keep in graph. + * @return {Observable} Observable emitting a single item, + * the graph, when it has been reset. + */ + GraphService.prototype.reset$ = function (keepKeys) { + this._abortSubjects(this._firstGraphSubjects$); + this._resetSubscriptions(this._initializeCacheSubscriptions); + this._resetSubscriptions(this._sequenceSubscriptions); + this._resetSubscriptions(this._spatialSubscriptions); + return this._graph$ + .first() + .do(function (graph) { + graph.reset(keepKeys); + }) + .map(function (graph) { + return undefined; + }); + }; + /** + * Uncache the graph. + * + * @description Uncaches the graph by removing tiles, nodes and + * sequences. Keeps the nodes of the supplied keys and the tiles + * related to those nodes. + * + * @param {Array} keepKeys - Keys of nodes to keep in graph. + * @param {string} keepSequenceKey - Optional key of sequence + * for which the belonging nodes should not be disposed or + * removed from the graph. These nodes may still be uncached if + * not specified in keep keys param. + * @return {Observable} Observable emitting a single item, + * the graph, when the graph has been uncached. + */ + GraphService.prototype.uncache$ = function (keepKeys, keepSequenceKey) { + return this._graph$ + .first() + .do(function (graph) { + graph.uncache(keepKeys, keepSequenceKey); + }) + .map(function (graph) { + return undefined; }); }; - GraphService.prototype._removeSpatialSubscription = function (spatialSubscription) { - var index = this._spatialSubscriptions.indexOf(spatialSubscription); - if (index > -1) { - this._spatialSubscriptions.splice(index, 1); + GraphService.prototype._abortSubjects = function (subjects) { + for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) { + var subject = _a[_i]; + this._removeFromArray(subject, subjects); + subject.error(new Error("Cache node request was aborted.")); + } + }; + GraphService.prototype._removeFromArray = function (object, objects) { + var index = objects.indexOf(object); + if (index !== -1) { + objects.splice(index, 1); } }; - GraphService.prototype._resetSpatialSubscriptions = function () { - for (var _i = 0, _a = this._spatialSubscriptions; _i < _a.length; _i++) { + GraphService.prototype._resetSubscriptions = function (subscriptions) { + for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) { var subscription = _a[_i]; + this._removeFromArray(subscription, subscriptions); if (!subscription.closed) { subscription.unsubscribe(); } } - this._spatialSubscriptions = []; }; return GraphService; }()); exports.GraphService = GraphService; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = GraphService; -},{"rxjs/Observable":28,"rxjs/add/operator/catch":48,"rxjs/add/operator/concat":50,"rxjs/add/operator/do":54,"rxjs/add/operator/expand":55,"rxjs/add/operator/finally":57,"rxjs/add/operator/first":58,"rxjs/add/operator/last":59,"rxjs/add/operator/map":60,"rxjs/add/operator/mergeMap":63,"rxjs/add/operator/publishReplay":67}],283:[function(require,module,exports){ +},{"../Graph":294,"rxjs/Observable":29,"rxjs/Subject":34}],400:[function(require,module,exports){ "use strict"; -var Observable_1 = require("rxjs/Observable"); -var Utils_1 = require("../Utils"); -var ImageLoader = (function () { - function ImageLoader() { - } - ImageLoader.loadThumbnail = function (key, imageSize) { - return this._load(key, imageSize, Utils_1.Urls.thumbnail); - }; - ImageLoader.loadDynamic = function (key, imageSize) { - return this._load(key, imageSize, Utils_1.Urls.dynamicImage); - }; - ImageLoader._load = function (key, size, getUrl) { - return Observable_1.Observable.create(function (subscriber) { - var image = new Image(); - image.crossOrigin = "Anonymous"; - var xmlHTTP = new XMLHttpRequest(); - xmlHTTP.open("GET", getUrl(key, size), true); - xmlHTTP.responseType = "arraybuffer"; - xmlHTTP.onload = function (pe) { - if (xmlHTTP.status !== 200) { - subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)); - return; - } - image.onload = function (e) { - subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image }); - subscriber.complete(); - }; - image.onerror = function (error) { - subscriber.error(new Error("Failed to load image (" + key + ")")); - }; - var blob = new Blob([xmlHTTP.response]); - image.src = window.URL.createObjectURL(blob); - }; - xmlHTTP.onprogress = function (pe) { - subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null }); - }; - xmlHTTP.onerror = function (error) { - subscriber.error(new Error("Failed to fetch image (" + key + ")")); - }; - xmlHTTP.send(null); - }); - }; - return ImageLoader; -}()); -exports.ImageLoader = ImageLoader; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = ImageLoader; - -},{"../Utils":215,"rxjs/Observable":28}],284:[function(require,module,exports){ /// -"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Subject_1 = require("rxjs/Subject"); -var ImageLoadingService = (function () { +var ImageLoadingService = /** @class */ (function () { function ImageLoadingService() { this._loadnode$ = new Subject_1.Subject(); this._loadstatus$ = this._loadnode$ - .scan(function (nodes, node) { - nodes[node.key] = node.loadStatus; + .scan(function (_a, node) { + var nodes = _a[0]; + var changed = false; + if (node.loadStatus.total === 0 || node.loadStatus.loaded === node.loadStatus.total) { + if (node.key in nodes) { + delete nodes[node.key]; + changed = true; + } + } + else { + nodes[node.key] = node.loadStatus; + changed = true; + } + return [nodes, changed]; + }, [{}, false]) + .filter(function (_a) { + var nodes = _a[0], changed = _a[1]; + return changed; + }) + .map(function (_a) { + var nodes = _a[0]; return nodes; - }, {}) + }) .publishReplay(1) .refCount(); - this._loadstatus$.subscribe(); + this._loadstatus$.subscribe(function () { }); } Object.defineProperty(ImageLoadingService.prototype, "loadnode$", { get: function () { @@ -27946,11 +39582,12 @@ var ImageLoadingService = (function () { }()); exports.ImageLoadingService = ImageLoadingService; -},{"rxjs/Subject":33}],285:[function(require,module,exports){ -/// +},{"rxjs/Subject":34}],401:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var Pbf = require("pbf"); -var MeshReader = (function () { +var MeshReader = /** @class */ (function () { function MeshReader() { } MeshReader.read = function (buffer) { @@ -27969,19 +39606,45 @@ var MeshReader = (function () { }()); exports.MeshReader = MeshReader; -},{"pbf":22}],286:[function(require,module,exports){ +},{"pbf":23}],402:[function(require,module,exports){ "use strict"; -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/operator/map"); +Object.defineProperty(exports, "__esModule", { value: true }); /** * @class Node * * @classdesc Represents a node in the navigation graph. + * + * Explanation of position and bearing properties: + * + * When images are uploaded they will have GPS information in the EXIF, this is what + * is called `originalLatLon` {@link Node.originalLatLon}. + * + * When Structure from Motions has been run for a node a `computedLatLon` that + * differs from the `originalLatLon` will be created. It is different because + * GPS positions are not very exact and SfM aligns the camera positions according + * to the 3D reconstruction {@link Node.computedLatLon}. + * + * At last there exist a `latLon` property which evaluates to + * the `computedLatLon` from SfM if it exists but falls back + * to the `originalLatLon` from the EXIF GPS otherwise {@link Node.latlon}. + * + * Everything that is done in in the Viewer is based on the SfM positions, + * i.e. `computedLatLon`. That is why the smooth transitions go in the right + * direction (nd not in strange directions because of bad GPS). + * + * E.g. when placing a marker in the Viewer it is relative to the SfM + * position i.e. the `computedLatLon`. + * + * The same concept as above also applies to the compass angle (or bearing) properties + * `originalCa`, `computedCa` and `ca`. */ -var Node = (function () { +var Node = /** @class */ (function () { /** * Create a new node instance. * + * @description Nodes are always created internally by the library. + * Nodes can not be added to the library through any API method. + * * @param {ICoreNode} coreNode - Raw core node data. */ function Node(core) { @@ -28053,6 +39716,22 @@ var Node = (function () { enumerable: true, configurable: true }); + Object.defineProperty(Node.prototype, "cameraUuid", { + /** + * Get camera uuid. + * + * @description Will be undefined if the camera uuid was not + * recorded in the image exif information. + * + * @returns {string} Universally unique id for camera used + * when capturing image. + */ + get: function () { + return this._fill.captured_with_camera_uuid; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Node.prototype, "computedCA", { /** * Get computedCA. @@ -28170,6 +39849,19 @@ var Node = (function () { enumerable: true, configurable: true }); + Object.defineProperty(Node.prototype, "image$", { + /** + * Get image$. + * + * @returns {Observable} Observable emitting + * the cached image when it is updated. + */ + get: function () { + return this._cache.image$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Node.prototype, "key", { /** * Get key. @@ -28271,6 +39963,20 @@ var Node = (function () { enumerable: true, configurable: true }); + Object.defineProperty(Node.prototype, "organizationKey", { + /** + * Get organizationKey. + * + * @returns {string} Unique key of the organization to which + * the node belongs. If the node does not belong to an + * organization the organization key will be undefined. + */ + get: function () { + return this._fill.organization_key; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Node.prototype, "orientation", { /** * Get orientation. @@ -28323,6 +40029,38 @@ var Node = (function () { enumerable: true, configurable: true }); + Object.defineProperty(Node.prototype, "private", { + /** + * Get private. + * + * @returns {boolean} Value specifying if image is accessible to + * organization members only or to everyone. + */ + get: function () { + return this._fill.private; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Node.prototype, "projectKey", { + /** + * Get projectKey. + * + * @returns {string} Unique key of the project to which + * the node belongs. If the node does not belong to a + * project the project key will be undefined. + * + * @deprecated This property will be deprecated in favor + * of the organization key and private properties. + */ + get: function () { + return this._fill.project != null ? + this._fill.project.key : + null; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(Node.prototype, "rotation", { /** * Get rotation. @@ -28359,7 +40097,7 @@ var Node = (function () { * the node belongs. */ get: function () { - return this._core.sequence.key; + return this._core.sequence_key; }, enumerable: true, configurable: true @@ -28471,6 +40209,13 @@ var Node = (function () { return _this; }); }; + Node.prototype.cacheImage$ = function (imageSize) { + var _this = this; + return this._cache.cacheImage$(this.key, imageSize) + .map(function (cache) { + return _this; + }); + }; /** * Cache the sequence edges. * @@ -28534,25 +40279,40 @@ var Node = (function () { } this._fill = fill; }; + /** + * Reset the sequence edges. + */ + Node.prototype.resetSequenceEdges = function () { + this._cache.resetSequenceEdges(); + }; /** * Reset the spatial edges. */ Node.prototype.resetSpatialEdges = function () { this._cache.resetSpatialEdges(); }; + /** + * Clears the image and mesh assets, aborts + * any outstanding requests and resets edges. + */ + Node.prototype.uncache = function () { + if (this._cache == null) { + return; + } + this._cache.dispose(); + this._cache = null; + }; return Node; }()); exports.Node = Node; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Node; -},{"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/map":60}],287:[function(require,module,exports){ +},{}],403:[function(require,module,exports){ (function (Buffer){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Subject_1 = require("rxjs/Subject"); var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/operator/publishReplay"); var Graph_1 = require("../Graph"); var Utils_1 = require("../Utils"); /** @@ -28560,28 +40320,35 @@ var Utils_1 = require("../Utils"); * * @classdesc Represents the cached properties of a node. */ -var NodeCache = (function () { +var NodeCache = /** @class */ (function () { /** * Create a new node cache instance. */ function NodeCache() { + this._disposed = false; this._image = null; this._loadStatus = { loaded: 0, total: 0 }; this._mesh = null; this._sequenceEdges = { cached: false, edges: [] }; this._spatialEdges = { cached: false, edges: [] }; + this._imageChanged$ = new Subject_1.Subject(); + this._image$ = this._imageChanged$ + .startWith(null) + .publishReplay(1) + .refCount(); + this._iamgeSubscription = this._image$.subscribe(); this._sequenceEdgesChanged$ = new Subject_1.Subject(); this._sequenceEdges$ = this._sequenceEdgesChanged$ .startWith(this._sequenceEdges) .publishReplay(1) .refCount(); - this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(); + this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { }); this._spatialEdgesChanged$ = new Subject_1.Subject(); this._spatialEdges$ = this._spatialEdgesChanged$ .startWith(this._spatialEdges) .publishReplay(1) .refCount(); - this._spatialEdgesSubscription = this._spatialEdges$.subscribe(); + this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { }); this._cachingAssets$ = null; } Object.defineProperty(NodeCache.prototype, "image", { @@ -28599,6 +40366,19 @@ var NodeCache = (function () { enumerable: true, configurable: true }); + Object.defineProperty(NodeCache.prototype, "image$", { + /** + * Get image$. + * + * @returns {Observable} Observable emitting + * the cached image when it is updated. + */ + get: function () { + return this._image$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(NodeCache.prototype, "loadStatus", { /** * Get loadStatus. @@ -28686,16 +40466,20 @@ var NodeCache = (function () { * @param {string} key - Key of the node to cache. * @param {boolean} pano - Value indicating whether node is a panorama. * @param {boolean} merged - Value indicating whether node is merged. - * @returns {Observable} Observable emitting this node whenever the - * load status has changed and when the mesh or image has been fully loaded. + * @returns {Observable} Observable emitting this node + * cache whenever the load status has changed and when the mesh or image + * has been fully loaded. */ NodeCache.prototype.cacheAssets$ = function (key, pano, merged) { var _this = this; if (this._cachingAssets$ != null) { return this._cachingAssets$; } + var imageSize = pano ? + Utils_1.Settings.basePanoramaSize : + Utils_1.Settings.baseImageSize; this._cachingAssets$ = Observable_1.Observable - .combineLatest(this._cacheImage(key, pano), this._cacheMesh(key, merged), function (imageStatus, meshStatus) { + .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) { _this._loadStatus.loaded = 0; _this._loadStatus.total = 0; if (meshStatus) { @@ -28715,8 +40499,49 @@ var NodeCache = (function () { }) .publishReplay(1) .refCount(); + this._cachingAssets$ + .first(function (nodeCache) { + return !!nodeCache._image; + }) + .subscribe(function (nodeCache) { + _this._imageChanged$.next(_this._image); + }, function (error) { }); return this._cachingAssets$; }; + /** + * Cache an image with a higher resolution than the current one. + * + * @param {string} key - Key of the node to cache. + * @param {ImageSize} imageSize - The size to cache. + * @returns {Observable} Observable emitting a single item, + * the node cache, when the image has been cached. If supplied image + * size is not larger than the current image size the node cache is + * returned immediately. + */ + NodeCache.prototype.cacheImage$ = function (key, imageSize) { + var _this = this; + if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) { + return Observable_1.Observable.of(this); + } + var cacheImage$ = this._cacheImage$(key, imageSize) + .first(function (status) { + return status.object != null; + }) + .do(function (status) { + _this._disposeImage(); + _this._image = status.object; + }) + .map(function (imageStatus) { + return _this; + }) + .publishReplay(1) + .refCount(); + cacheImage$ + .subscribe(function (nodeCache) { + _this._imageChanged$.next(_this._image); + }, function (error) { }); + return cacheImage$; + }; /** * Cache the sequence edges. * @@ -28742,15 +40567,32 @@ var NodeCache = (function () { * all streams. */ NodeCache.prototype.dispose = function () { + this._iamgeSubscription.unsubscribe(); this._sequenceEdgesSubscription.unsubscribe(); this._spatialEdgesSubscription.unsubscribe(); - this._image = null; + this._disposeImage(); this._mesh = null; - this._loadStatus = { loaded: 0, total: 0 }; + this._loadStatus.loaded = 0; + this._loadStatus.total = 0; this._sequenceEdges = { cached: false, edges: [] }; this._spatialEdges = { cached: false, edges: [] }; + this._imageChanged$.next(null); this._sequenceEdgesChanged$.next(this._sequenceEdges); this._spatialEdgesChanged$.next(this._spatialEdges); + this._disposed = true; + if (this._imageRequest != null) { + this._imageRequest.abort(); + } + if (this._meshRequest != null) { + this._meshRequest.abort(); + } + }; + /** + * Reset the sequence edges. + */ + NodeCache.prototype.resetSequenceEdges = function () { + this._sequenceEdges = { cached: false, edges: [] }; + this._sequenceEdgesChanged$.next(this._sequenceEdges); }; /** * Reset the spatial edges. @@ -28768,11 +40610,59 @@ var NodeCache = (function () { * emitting a load status object every time the load status changes * and completes when the image is fully loaded. */ - NodeCache.prototype._cacheImage = function (key, pano) { - var imageSize = pano ? - Utils_1.Settings.basePanoramaSize : - Utils_1.Settings.baseImageSize; - return Graph_1.ImageLoader.loadThumbnail(key, imageSize); + NodeCache.prototype._cacheImage$ = function (key, imageSize) { + var _this = this; + return Observable_1.Observable.create(function (subscriber) { + var xmlHTTP = new XMLHttpRequest(); + xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize, Utils_1.Urls.origin), true); + xmlHTTP.responseType = "arraybuffer"; + xmlHTTP.timeout = 15000; + xmlHTTP.onload = function (pe) { + if (xmlHTTP.status !== 200) { + _this._imageRequest = null; + subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)); + return; + } + var image = new Image(); + image.crossOrigin = "Anonymous"; + image.onload = function (e) { + _this._imageRequest = null; + if (_this._disposed) { + window.URL.revokeObjectURL(image.src); + subscriber.error(new Error("Image load was aborted (" + key + ")")); + return; + } + subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image }); + subscriber.complete(); + }; + image.onerror = function (error) { + _this._imageRequest = null; + subscriber.error(new Error("Failed to load image (" + key + ")")); + }; + var blob = new Blob([xmlHTTP.response]); + image.src = window.URL.createObjectURL(blob); + }; + xmlHTTP.onprogress = function (pe) { + if (_this._disposed) { + return; + } + subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null }); + }; + xmlHTTP.onerror = function (error) { + _this._imageRequest = null; + subscriber.error(new Error("Failed to fetch image (" + key + ")")); + }; + xmlHTTP.ontimeout = function (e) { + _this._imageRequest = null; + subscriber.error(new Error("Image request timed out (" + key + ")")); + }; + xmlHTTP.onabort = function (event) { + _this._imageRequest = null; + subscriber.error(new Error("Image request was aborted (" + key + ")")); + }; + _this._imageRequest = xmlHTTP; + xmlHTTP.send(null); + }); }; /** * Cache the mesh. @@ -28783,7 +40673,7 @@ var NodeCache = (function () { * a load status object every time the load status changes and completes * when the mesh is fully loaded. */ - NodeCache.prototype._cacheMesh = function (key, merged) { + NodeCache.prototype._cacheMesh$ = function (key, merged) { var _this = this; return Observable_1.Observable.create(function (subscriber) { if (!merged) { @@ -28794,7 +40684,12 @@ var NodeCache = (function () { var xmlHTTP = new XMLHttpRequest(); xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true); xmlHTTP.responseType = "arraybuffer"; + xmlHTTP.timeout = 15000; xmlHTTP.onload = function (pe) { + _this._meshRequest = null; + if (_this._disposed) { + return; + } var mesh = xmlHTTP.status === 200 ? Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) : { faces: [], vertices: [] }; @@ -28802,13 +40697,28 @@ var NodeCache = (function () { subscriber.complete(); }; xmlHTTP.onprogress = function (pe) { + if (_this._disposed) { + return; + } subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null }); }; xmlHTTP.onerror = function (e) { + _this._meshRequest = null; console.error("Failed to cache mesh (" + key + ")"); subscriber.next(_this._createEmptyMeshLoadStatus()); subscriber.complete(); }; + xmlHTTP.ontimeout = function (e) { + _this._meshRequest = null; + console.error("Mesh request timed out (" + key + ")"); + subscriber.next(_this._createEmptyMeshLoadStatus()); + subscriber.complete(); + }; + xmlHTTP.onabort = function (e) { + _this._meshRequest = null; + subscriber.error(new Error("Mesh request was aborted (" + key + ")")); + }; + _this._meshRequest = xmlHTTP; xmlHTTP.send(null); }); }; @@ -28824,24 +40734,30 @@ var NodeCache = (function () { object: { faces: [], vertices: [] }, }; }; + NodeCache.prototype._disposeImage = function () { + if (this._image != null) { + window.URL.revokeObjectURL(this._image.src); + } + this._image = null; + }; return NodeCache; }()); exports.NodeCache = NodeCache; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = NodeCache; }).call(this,require("buffer").Buffer) -},{"../Graph":211,"../Utils":215,"buffer":5,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/publishReplay":67}],288:[function(require,module,exports){ -/// +},{"../Graph":294,"../Utils":300,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34}],404:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var _ = require("underscore"); /** * @class Sequence * * @classdesc Represents a sequence of ordered nodes. */ -var Sequence = (function () { +var Sequence = /** @class */ (function () { /** * Create a new sequene instance. * @@ -28875,6 +40791,15 @@ var Sequence = (function () { enumerable: true, configurable: true }); + /** + * Dispose the sequence. + * + * @description Disposes all cached assets. + */ + Sequence.prototype.dispose = function () { + this._key = null; + this._keys = null; + }; /** * Find the next node key in the sequence with respect to * the provided node key. @@ -28910,12 +40835,12 @@ var Sequence = (function () { return Sequence; }()); exports.Sequence = Sequence; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Sequence; -},{"underscore":158}],289:[function(require,module,exports){ -/// +},{"underscore":242}],405:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); var Edge_1 = require("../../Edge"); var Error_1 = require("../../Error"); @@ -28925,7 +40850,7 @@ var Geo_1 = require("../../Geo"); * * @classdesc Represents a class for calculating node edges. */ -var EdgeCalculator = (function () { +var EdgeCalculator = /** @class */ (function () { /** * Create a new edge calculator instance. * @@ -28989,6 +40914,7 @@ var EdgeCalculator = (function () { var sameUser = potential.userKey === node.userKey; var potentialEdge = { capturedAt: potential.capturedAt, + croppedPano: potential.pano && !potential.fullPano, directionChange: directionChange, distance: distance, fullPano: potential.fullPano, @@ -29068,8 +40994,7 @@ var EdgeCalculator = (function () { if (potentialEdge.sequenceKey == null) { continue; } - if (potentialEdge.sameSequence || - !potentialEdge.sameMergeCC) { + if (potentialEdge.sameSequence) { continue; } if (nodeFullPano) { @@ -29139,6 +41064,9 @@ var EdgeCalculator = (function () { /** * Computes the step edges for a perspective node. * + * @description Step edge targets can only be other perspective nodes. + * Returns an empty array for cropped and full panoramas. + * * @param {Node} node - Source node. * @param {Array} potentialEdges - Potential edges. * @param {string} prevKey - Key of previous node in sequence. @@ -29150,7 +41078,7 @@ var EdgeCalculator = (function () { throw new Error_1.ArgumentMapillaryError("Node has to be full."); } var edges = []; - if (node.fullPano) { + if (node.pano) { return edges; } for (var k in this._directions.steps) { @@ -29163,7 +41091,7 @@ var EdgeCalculator = (function () { var fallback = null; for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) { var potential = potentialEdges_2[_i]; - if (potential.fullPano) { + if (potential.croppedPano || potential.fullPano) { continue; } if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) { @@ -29213,6 +41141,9 @@ var EdgeCalculator = (function () { /** * Computes the turn edges for a perspective node. * + * @description Turn edge targets can only be other perspective images. + * Returns an empty array for cropped and full panoramas. + * * @param {Node} node - Source node. * @param {Array} potentialEdges - Potential edges. * @throws {ArgumentMapillaryError} If node is not full. @@ -29222,7 +41153,7 @@ var EdgeCalculator = (function () { throw new Error_1.ArgumentMapillaryError("Node has to be full."); } var edges = []; - if (node.fullPano) { + if (node.pano) { return edges; } for (var k in this._directions.turns) { @@ -29234,7 +41165,7 @@ var EdgeCalculator = (function () { var edge = null; for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) { var potential = potentialEdges_3[_i]; - if (potential.fullPano) { + if (potential.croppedPano || potential.fullPano) { continue; } if (potential.distance > this._settings.turnMaxDistance) { @@ -29286,6 +41217,9 @@ var EdgeCalculator = (function () { /** * Computes the pano edges for a perspective node. * + * @description Perspective to pano edge targets can only be + * full pano nodes. Returns an empty array for cropped and full panoramas. + * * @param {Node} node - Source node. * @param {Array} potentialEdges - Potential edges. * @throws {ArgumentMapillaryError} If node is not full. @@ -29294,7 +41228,7 @@ var EdgeCalculator = (function () { if (!node.full) { throw new Error_1.ArgumentMapillaryError("Node has to be full."); } - if (node.fullPano) { + if (node.pano) { return []; } var lowestScore = Number.MAX_VALUE; @@ -29329,7 +41263,12 @@ var EdgeCalculator = (function () { ]; }; /** - * Computes the pano and step edges for a pano node. + * Computes the full pano and step edges for a full pano node. + * + * @description Pano to pano edge targets can only be + * full pano nodes. Pano to step edge targets can only be perspective + * nodes. + * Returns an empty array for cropped panoramas and perspective nodes. * * @param {Node} node - Source node. * @param {Array} potentialEdges - Potential edges. @@ -29357,6 +41296,9 @@ var EdgeCalculator = (function () { potentialPanos.push(potential); } else { + if (potential.croppedPano) { + continue; + } for (var k in this._directions.panos) { if (!this._directions.panos.hasOwnProperty(k)) { continue; @@ -29495,12 +41437,12 @@ var EdgeCalculator = (function () { return EdgeCalculator; }()); exports.EdgeCalculator = EdgeCalculator; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = EdgeCalculator; -},{"../../Edge":208,"../../Error":209,"../../Geo":210,"three":157}],290:[function(require,module,exports){ +},{"../../Edge":291,"../../Error":292,"../../Geo":293,"three":240}],406:[function(require,module,exports){ "use strict"; -var EdgeCalculatorCoefficients = (function () { +Object.defineProperty(exports, "__esModule", { value: true }); +var EdgeCalculatorCoefficients = /** @class */ (function () { function EdgeCalculatorCoefficients() { this.panoPreferredDistance = 2; this.panoMotion = 2; @@ -29521,13 +41463,13 @@ var EdgeCalculatorCoefficients = (function () { return EdgeCalculatorCoefficients; }()); exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = EdgeCalculatorCoefficients; -},{}],291:[function(require,module,exports){ +},{}],407:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Edge_1 = require("../../Edge"); -var EdgeCalculatorDirections = (function () { +var EdgeCalculatorDirections = /** @class */ (function () { function EdgeCalculatorDirections() { this.steps = {}; this.turns = {}; @@ -29596,9 +41538,10 @@ var EdgeCalculatorDirections = (function () { }()); exports.EdgeCalculatorDirections = EdgeCalculatorDirections; -},{"../../Edge":208}],292:[function(require,module,exports){ +},{"../../Edge":291}],408:[function(require,module,exports){ "use strict"; -var EdgeCalculatorSettings = (function () { +Object.defineProperty(exports, "__esModule", { value: true }); +var EdgeCalculatorSettings = /** @class */ (function () { function EdgeCalculatorSettings() { this.panoMinDistance = 0.1; this.panoMaxDistance = 20; @@ -29630,11 +41573,11 @@ var EdgeCalculatorSettings = (function () { return EdgeCalculatorSettings; }()); exports.EdgeCalculatorSettings = EdgeCalculatorSettings; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = EdgeCalculatorSettings; -},{}],293:[function(require,module,exports){ +},{}],409:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); /** * Enumeration for edge directions * @enum {number} @@ -29642,6 +41585,7 @@ exports.default = EdgeCalculatorSettings; * @description Directions for edges in node graph describing * sequence, spatial and node type relations between nodes. */ +var EdgeDirection; (function (EdgeDirection) { /** * Next node in the sequence. @@ -29687,24 +41631,17 @@ exports.default = EdgeCalculatorSettings; * Looking in roughly the same direction at rougly the same position. */ EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar"; -})(exports.EdgeDirection || (exports.EdgeDirection = {})); -var EdgeDirection = exports.EdgeDirection; -; +})(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {})); -},{}],294:[function(require,module,exports){ -/// +},{}],410:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var _ = require("underscore"); var vd = require("virtual-dom"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/combineLatest"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/pluck"); -require("rxjs/add/operator/scan"); var Render_1 = require("../Render"); -var DOMRenderer = (function () { +var DOMRenderer = /** @class */ (function () { function DOMRenderer(element, renderService, currentFrame$) { this._adaptiveOperation$ = new Subject_1.Subject(); this._render$ = new Subject_1.Subject(); @@ -29790,10 +41727,10 @@ var DOMRenderer = (function () { style: { bottom: offset.bottom + "px", left: offset.left + "px", + "pointer-events": "none", position: "absolute", right: offset.right + "px", top: offset.top + "px", - zIndex: -1, }, }; return { @@ -29829,7 +41766,7 @@ var DOMRenderer = (function () { }, rootNode) .publishReplay(1) .refCount(); - this._element$.subscribe(); + this._element$.subscribe(function () { }); this._renderService.size$ .map(function (size) { return function (adaptive) { @@ -29876,38 +41813,29 @@ var DOMRenderer = (function () { return DOMRenderer; }()); exports.DOMRenderer = DOMRenderer; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = DOMRenderer; -},{"../Render":213,"rxjs/Subject":33,"rxjs/add/operator/combineLatest":49,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/pluck":65,"rxjs/add/operator/scan":68,"underscore":158,"virtual-dom":163}],295:[function(require,module,exports){ +},{"../Render":296,"rxjs/Subject":34,"underscore":242,"virtual-dom":246}],411:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var GLRenderStage; (function (GLRenderStage) { GLRenderStage[GLRenderStage["Background"] = 0] = "Background"; GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground"; -})(exports.GLRenderStage || (exports.GLRenderStage = {})); -var GLRenderStage = exports.GLRenderStage; -Object.defineProperty(exports, "__esModule", { value: true }); +})(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {})); exports.default = GLRenderStage; -},{}],296:[function(require,module,exports){ -/// +},{}],412:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/first"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/merge"); -require("rxjs/add/operator/mergeMap"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/share"); -require("rxjs/add/operator/startWith"); var Render_1 = require("../Render"); -var GLRenderer = (function () { - function GLRenderer(renderService) { +var Utils_1 = require("../Utils"); +var GLRenderer = /** @class */ (function () { + function GLRenderer(canvasContainer, renderService, dom) { var _this = this; this._renderFrame$ = new Subject_1.Subject(); this._renderCameraOperation$ = new Subject_1.Subject(); @@ -29917,10 +41845,14 @@ var GLRenderer = (function () { this._rendererOperation$ = new Subject_1.Subject(); this._eraserOperation$ = new Subject_1.Subject(); this._renderService = renderService; + this._dom = !!dom ? dom : new Utils_1.DOM(); this._renderer$ = this._rendererOperation$ .scan(function (renderer, operation) { return operation(renderer); - }, { needsRender: false, renderer: null }); + }, { needsRender: false, renderer: null }) + .filter(function (renderer) { + return !!renderer.renderer; + }); this._renderCollection$ = this._renderOperation$ .scan(function (hashes, operation) { return operation(hashes); @@ -29981,7 +41913,6 @@ var GLRenderer = (function () { } } var renderer = co.renderer.renderer; - renderer.autoClear = false; renderer.clear(); for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) { var render = backgroundRenders_1[_b]; @@ -30023,18 +41954,28 @@ var GLRenderer = (function () { Observable_1.Observable .merge(renderHash$, clearHash$) .subscribe(this._renderOperation$); - var createRenderer$ = this._render$ + this._webGLRenderer$ = this._render$ .first() .map(function (hash) { + var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas"); + canvas.style.position = "absolute"; + canvas.setAttribute("tabindex", "0"); + canvasContainer.appendChild(canvas); + var element = renderService.element; + var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas }); + webGLRenderer.setPixelRatio(window.devicePixelRatio); + webGLRenderer.setSize(element.offsetWidth, element.offsetHeight); + webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0); + webGLRenderer.autoClear = false; + return webGLRenderer; + }) + .publishReplay(1) + .refCount(); + this._webGLRenderer$.subscribe(function () { }); + var createRenderer$ = this._webGLRenderer$ + .first() + .map(function (webGLRenderer) { return function (renderer) { - var webGLRenderer = new THREE.WebGLRenderer(); - var element = renderService.element; - webGLRenderer.setSize(element.offsetWidth, element.offsetHeight); - webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0); - webGLRenderer.sortObjects = false; - webGLRenderer.domElement.style.width = "100%"; - webGLRenderer.domElement.style.height = "100%"; - element.appendChild(webGLRenderer.domElement); renderer.needsRender = true; renderer.renderer = webGLRenderer; return renderer; @@ -30094,6 +42035,13 @@ var GLRenderer = (function () { enumerable: true, configurable: true }); + Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", { + get: function () { + return this._webGLRenderer$; + }, + enumerable: true, + configurable: true + }); GLRenderer.prototype.clear = function (name) { this._clear$.next(name); }; @@ -30120,17 +42068,17 @@ var GLRenderer = (function () { return GLRenderer; }()); exports.GLRenderer = GLRenderer; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = GLRenderer; -},{"../Render":213,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/first":58,"rxjs/add/operator/map":60,"rxjs/add/operator/merge":61,"rxjs/add/operator/mergeMap":63,"rxjs/add/operator/scan":68,"rxjs/add/operator/share":69,"rxjs/add/operator/startWith":72,"three":157}],297:[function(require,module,exports){ -/// +},{"../Render":296,"../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34,"three":240}],413:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); var Geo_1 = require("../Geo"); var Render_1 = require("../Render"); -var RenderCamera = (function () { - function RenderCamera(perspectiveCameraAspect, renderMode) { +var RenderCamera = /** @class */ (function () { + function RenderCamera(elementWidth, elementHeight, renderMode) { this.alpha = -1; this.zoom = 0; this._frameId = -1; @@ -30141,16 +42089,13 @@ var RenderCamera = (function () { this.previousAspect = 1; this.previousPano = false; this.renderMode = renderMode; + this._spatial = new Geo_1.Spatial(); this._camera = new Geo_1.Camera(); + var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight); this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000); + this._perspective.matrixAutoUpdate = false; + this._rotation = { phi: 0, theta: 0 }; } - Object.defineProperty(RenderCamera.prototype, "perspective", { - get: function () { - return this._perspective; - }, - enumerable: true, - configurable: true - }); Object.defineProperty(RenderCamera.prototype, "camera", { get: function () { return this._camera; @@ -30179,6 +42124,25 @@ var RenderCamera = (function () { enumerable: true, configurable: true }); + Object.defineProperty(RenderCamera.prototype, "perspective", { + get: function () { + return this._perspective; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RenderCamera.prototype, "rotation", { + get: function () { + return this._rotation; + }, + enumerable: true, + configurable: true + }); + RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) { + var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight); + this._perspective.aspect = perspectiveCameraAspect; + this._changed = true; + }; RenderCamera.prototype.updateProjection = function () { var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect); var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect); @@ -30192,8 +42156,13 @@ var RenderCamera = (function () { this._perspective.up.copy(camera.up); this._perspective.position.copy(camera.position); this._perspective.lookAt(camera.lookat); + this._perspective.updateMatrix(); + this._perspective.updateMatrixWorld(false); this._changed = true; }; + RenderCamera.prototype.updateRotation = function (camera) { + this._rotation = this._getRotation(camera); + }; RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) { return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI; }; @@ -30210,14 +42179,26 @@ var RenderCamera = (function () { coeff * nodeAspect; return aspect; }; + RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) { + return elementWidth === 0 ? 0 : elementWidth / elementHeight; + }; + RenderCamera.prototype._getRotation = function (camera) { + var direction = camera.lookat.clone().sub(camera.position); + var up = camera.up.clone(); + var upProjection = direction.clone().dot(up); + var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection)); + var phi = Math.atan2(planeProjection.y, planeProjection.x); + var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]); + return { phi: phi, theta: theta }; + }; return RenderCamera; }()); exports.RenderCamera = RenderCamera; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = RenderCamera; -},{"../Geo":210,"../Render":213,"three":157}],298:[function(require,module,exports){ +},{"../Geo":293,"../Render":296,"three":240}],414:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); /** * Enumeration for render mode * @enum {number} @@ -30226,6 +42207,7 @@ exports.default = RenderCamera; * in the viewer. All modes preserves the original aspect * ratio of the images. */ +var RenderMode; (function (RenderMode) { /** * Displays all content within the viewer. @@ -30247,31 +42229,23 @@ exports.default = RenderCamera; * between the image and the viewer. */ RenderMode[RenderMode["Fill"] = 1] = "Fill"; -})(exports.RenderMode || (exports.RenderMode = {})); -var RenderMode = exports.RenderMode; -Object.defineProperty(exports, "__esModule", { value: true }); +})(RenderMode = exports.RenderMode || (exports.RenderMode = {})); exports.default = RenderMode; -},{}],299:[function(require,module,exports){ -/// +},{}],415:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var Subject_1 = require("rxjs/Subject"); var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/operator/do"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/skip"); -require("rxjs/add/operator/startWith"); -require("rxjs/add/operator/withLatestFrom"); +var Geo_1 = require("../Geo"); var Render_1 = require("../Render"); -var RenderService = (function () { +var RenderService = /** @class */ (function () { function RenderService(element, currentFrame$, renderMode) { var _this = this; this._element = element; this._currentFrame$ = currentFrame$; + this._spatial = new Geo_1.Spatial(); renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill; this._resize$ = new Subject_1.Subject(); this._renderCameraOperation$ = new Subject_1.Subject(); @@ -30292,7 +42266,7 @@ var RenderService = (function () { }) .scan(function (rc, operation) { return operation(rc); - }, new Render_1.RenderCamera(this._element.offsetWidth / this._element.offsetHeight, renderMode)) + }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode)) .publishReplay(1) .refCount(); this._renderCameraFrame$ = this._currentFrame$ @@ -30305,7 +42279,7 @@ var RenderService = (function () { var camera = frame.state.camera; if (rc.alpha !== frame.state.alpha || rc.zoom !== frame.state.zoom || - rc.camera.diff(camera) > 1e-5) { + rc.camera.diff(camera) > 1e-9) { var currentTransform = frame.state.currentTransform; var previousTransform = frame.state.previousTransform != null ? frame.state.previousTransform : @@ -30321,6 +42295,7 @@ var RenderService = (function () { rc.zoom = frame.state.zoom; rc.camera.copy(camera); rc.updatePerspective(camera); + rc.updateRotation(camera); rc.updateProjection(); } rc.frameId = frame.id; @@ -30336,11 +42311,18 @@ var RenderService = (function () { }) .publishReplay(1) .refCount(); + this._bearing$ = this._renderCamera$ + .map(function (renderCamera) { + var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi)); + return _this._spatial.wrap(bearing, 0, 360); + }) + .publishReplay(1) + .refCount(); this._size$ .skip(1) .map(function (size) { return function (rc) { - rc.perspective.aspect = size.width / size.height; + rc.updateAspect(size.width, size.height); rc.updateProjection(); return rc; }; @@ -30356,10 +42338,20 @@ var RenderService = (function () { }; }) .subscribe(this._renderCameraOperation$); - this._renderCameraHolder$.subscribe(); - this._size$.subscribe(); - this._renderMode$.subscribe(); - } + this._bearing$.subscribe(function () { }); + this._renderCameraHolder$.subscribe(function () { }); + this._size$.subscribe(function () { }); + this._renderMode$.subscribe(function () { }); + this._renderCamera$.subscribe(function () { }); + this._renderCameraFrame$.subscribe(function () { }); + } + Object.defineProperty(RenderService.prototype, "bearing$", { + get: function () { + return this._bearing$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(RenderService.prototype, "element", { get: function () { return this._element; @@ -30405,73 +42397,96 @@ var RenderService = (function () { return RenderService; }()); exports.RenderService = RenderService; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = RenderService; -},{"../Render":213,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/do":54,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/skip":70,"rxjs/add/operator/startWith":72,"rxjs/add/operator/withLatestFrom":76}],300:[function(require,module,exports){ -/// +},{"../Geo":293,"../Render":296,"rxjs/BehaviorSubject":26,"rxjs/Subject":34}],416:[function(require,module,exports){ "use strict"; -var FrameGenerator = (function () { - function FrameGenerator() { - if (window.requestAnimationFrame) { - this._requestAnimationFrame = window.requestAnimationFrame; - this._cancelAnimationFrame = window.cancelAnimationFrame; - } - else if (window.mozRequestAnimationFrame) { - this._requestAnimationFrame = window.mozRequestAnimationFrame; - this._cancelAnimationFrame = window.mozCancelAnimationFrame; - } - else if (window.webkitRequestAnimationFrame) { - this._requestAnimationFrame = window.webkitRequestAnimationFrame; - this._cancelAnimationFrame = window.webkitCancelAnimationFrame; - } - else if (window.msRequestAnimationFrame) { - this._requestAnimationFrame = window.msRequestAnimationFrame; - this._cancelAnimationFrame = window.msCancelRequestAnimationFrame; - } - else if (window.oRequestAnimationFrame) { - this._requestAnimationFrame = window.oRequestAnimationFrame; - this._cancelAnimationFrame = window.oCancelAnimationFrame; - } - else { - this._requestAnimationFrame = function (callback) { - return window.setTimeout(callback, 1000 / 60); - }; - this._cancelAnimationFrame = window.clearTimeout; - } +Object.defineProperty(exports, "__esModule", { value: true }); +var RotationDelta = /** @class */ (function () { + function RotationDelta(phi, theta) { + this._phi = phi; + this._theta = theta; } - FrameGenerator.prototype.requestAnimationFrame = function (callback) { - return this._requestAnimationFrame.call(window, callback); + Object.defineProperty(RotationDelta.prototype, "phi", { + get: function () { + return this._phi; + }, + set: function (value) { + this._phi = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RotationDelta.prototype, "theta", { + get: function () { + return this._theta; + }, + set: function (value) { + this._theta = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RotationDelta.prototype, "isZero", { + get: function () { + return this._phi === 0 && this._theta === 0; + }, + enumerable: true, + configurable: true + }); + RotationDelta.prototype.copy = function (delta) { + this._phi = delta.phi; + this._theta = delta.theta; + }; + RotationDelta.prototype.lerp = function (other, alpha) { + this._phi = (1 - alpha) * this._phi + alpha * other.phi; + this._theta = (1 - alpha) * this._theta + alpha * other.theta; + }; + RotationDelta.prototype.multiply = function (value) { + this._phi *= value; + this._theta *= value; + }; + RotationDelta.prototype.threshold = function (value) { + this._phi = Math.abs(this._phi) > value ? this._phi : 0; + this._theta = Math.abs(this._theta) > value ? this._theta : 0; + }; + RotationDelta.prototype.lengthSquared = function () { + return this._phi * this._phi + this._theta * this._theta; }; - FrameGenerator.prototype.cancelAnimationFrame = function (id) { - this._cancelAnimationFrame.call(window, id); + RotationDelta.prototype.reset = function () { + this._phi = 0; + this._theta = 0; }; - return FrameGenerator; + return RotationDelta; }()); -exports.FrameGenerator = FrameGenerator; +exports.RotationDelta = RotationDelta; +exports.default = RotationDelta; -},{}],301:[function(require,module,exports){ +},{}],417:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var State; (function (State) { State[State["Traversing"] = 0] = "Traversing"; State[State["Waiting"] = 1] = "Waiting"; -})(exports.State || (exports.State = {})); -var State = exports.State; -Object.defineProperty(exports, "__esModule", { value: true }); + State[State["WaitingInteractively"] = 2] = "WaitingInteractively"; +})(State = exports.State || (exports.State = {})); exports.default = State; -},{}],302:[function(require,module,exports){ +},{}],418:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var State_1 = require("../State"); var Geo_1 = require("../Geo"); -var StateContext = (function () { - function StateContext() { +var StateContext = /** @class */ (function () { + function StateContext(transitionMode) { this._state = new State_1.TraversingState({ alpha: 1, camera: new Geo_1.Camera(), currentIndex: -1, reference: { alt: 0, lat: 0, lon: 0 }, trajectory: [], + transitionMode: transitionMode == null ? State_1.TransitionMode.Default : transitionMode, zoom: 0, }); } @@ -30481,6 +42496,9 @@ var StateContext = (function () { StateContext.prototype.wait = function () { this._state = this._state.wait(); }; + StateContext.prototype.waitInteractively = function () { + this._state = this._state.waitInteractively(); + }; Object.defineProperty(StateContext.prototype, "state", { get: function () { if (this._state instanceof State_1.TraversingState) { @@ -30489,6 +42507,9 @@ var StateContext = (function () { else if (this._state instanceof State_1.WaitingState) { return State_1.State.Waiting; } + else if (this._state instanceof State_1.InteractiveWaitingState) { + return State_1.State.WaitingInteractively; + } throw new Error("Invalid state"); }, enumerable: true, @@ -30613,6 +42634,12 @@ var StateContext = (function () { StateContext.prototype.remove = function (n) { this._state.remove(n); }; + StateContext.prototype.clear = function () { + this._state.clear(); + }; + StateContext.prototype.clearPrior = function () { + this._state.clearPrior(); + }; StateContext.prototype.cut = function () { this._state.cut(); }; @@ -30625,6 +42652,12 @@ var StateContext = (function () { StateContext.prototype.rotateBasic = function (basicRotation) { this._state.rotateBasic(basicRotation); }; + StateContext.prototype.rotateBasicUnbounded = function (basicRotation) { + this._state.rotateBasicUnbounded(basicRotation); + }; + StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) { + this._state.rotateBasicWithoutInertia(basicRotation); + }; StateContext.prototype.rotateToBasic = function (basic) { this._state.rotateToBasic(basic); }; @@ -30637,28 +42670,25 @@ var StateContext = (function () { StateContext.prototype.zoomIn = function (delta, reference) { this._state.zoomIn(delta, reference); }; + StateContext.prototype.setSpeed = function (speed) { + this._state.setSpeed(speed); + }; + StateContext.prototype.setTransitionMode = function (mode) { + this._state.setTransitionMode(mode); + }; return StateContext; }()); exports.StateContext = StateContext; -},{"../Geo":210,"../State":214}],303:[function(require,module,exports){ +},{"../Geo":293,"../State":297}],419:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/do"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/first"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/pairwise"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/startWith"); -require("rxjs/add/operator/switchMap"); -require("rxjs/add/operator/withLatestFrom"); +var AnimationFrame_1 = require("rxjs/util/AnimationFrame"); var State_1 = require("../State"); -var StateService = (function () { - function StateService() { +var StateService = /** @class */ (function () { + function StateService(transitionMode) { var _this = this; this._appendNode$ = new Subject_1.Subject(); this._start$ = new Subject_1.Subject(); @@ -30670,7 +42700,7 @@ var StateService = (function () { this._context$ = this._contextOperation$ .scan(function (context, operation) { return operation(context); - }, new State_1.StateContext()) + }, new State_1.StateContext(transitionMode)) .publishReplay(1) .refCount(); this._state$ = this._context$ @@ -30683,10 +42713,8 @@ var StateService = (function () { this._fps$ = this._start$ .switchMap(function () { return _this._frame$ - .filter(function (frameId) { - return frameId % _this._fpsSampleRate === 0; - }) - .map(function (frameId) { + .bufferCount(1, _this._fpsSampleRate) + .map(function (frameIds) { return new Date().getTime(); }) .pairwise() @@ -30720,7 +42748,14 @@ var StateService = (function () { .publishReplay(1) .refCount(); var nodeChangedSubject$ = new Subject_1.Subject(); - nodeChanged$.subscribe(nodeChangedSubject$); + nodeChanged$ + .subscribe(nodeChangedSubject$); + this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null); + nodeChangedSubject$ + .map(function (f) { + return f.state.currentNode.key; + }) + .subscribe(this._currentKey$); this._currentNode$ = nodeChangedSubject$ .map(function (f) { return f.state.currentNode; @@ -30764,13 +42799,13 @@ var StateService = (function () { }; }) .subscribe(this._contextOperation$); - this._movingOperation$ = new Subject_1.Subject(); + this._inMotionOperation$ = new Subject_1.Subject(); nodeChanged$ .map(function (frame) { return true; }) - .subscribe(this._movingOperation$); - this._movingOperation$ + .subscribe(this._inMotionOperation$); + this._inMotionOperation$ .distinctUntilChanged() .filter(function (moving) { return moving; @@ -30795,19 +42830,54 @@ var StateService = (function () { return !changed; }); }) - .subscribe(this._movingOperation$); - this._moving$ = this._movingOperation$ + .subscribe(this._inMotionOperation$); + this._inMotion$ = this._inMotionOperation$ .distinctUntilChanged() - .share(); - this._state$.subscribe(); - this._currentNode$.subscribe(); - this._currentCamera$.subscribe(); - this._currentTransform$.subscribe(); - this._reference$.subscribe(); - this._currentNodeExternal$.subscribe(); - this._lastState$.subscribe(); + .publishReplay(1) + .refCount(); + this._inTranslationOperation$ = new Subject_1.Subject(); + nodeChanged$ + .map(function (frame) { + return true; + }) + .subscribe(this._inTranslationOperation$); + this._inTranslationOperation$ + .distinctUntilChanged() + .filter(function (inTranslation) { + return inTranslation; + }) + .switchMap(function (inTranslation) { + return _this._currentState$ + .filter(function (frame) { + return frame.state.nodesAhead === 0; + }) + .map(function (frame) { + return frame.state.camera.position.clone(); + }) + .pairwise() + .map(function (pair) { + return pair[0].distanceToSquared(pair[1]) !== 0; + }) + .first(function (changed) { + return !changed; + }); + }) + .subscribe(this._inTranslationOperation$); + this._inTranslation$ = this._inTranslationOperation$ + .distinctUntilChanged() + .publishReplay(1) + .refCount(); + this._state$.subscribe(function () { }); + this._currentNode$.subscribe(function () { }); + this._currentCamera$.subscribe(function () { }); + this._currentTransform$.subscribe(function () { }); + this._reference$.subscribe(function () { }); + this._currentNodeExternal$.subscribe(function () { }); + this._lastState$.subscribe(function () { }); + this._inMotion$.subscribe(function () { }); + this._inTranslation$.subscribe(function () { }); this._frameId = null; - this._frameGenerator = new State_1.FrameGenerator(); + this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window); } Object.defineProperty(StateService.prototype, "currentState$", { get: function () { @@ -30823,6 +42893,13 @@ var StateService = (function () { enumerable: true, configurable: true }); + Object.defineProperty(StateService.prototype, "currentKey$", { + get: function () { + return this._currentKey$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(StateService.prototype, "currentNodeExternal$", { get: function () { return this._currentNodeExternal$; @@ -30858,9 +42935,16 @@ var StateService = (function () { enumerable: true, configurable: true }); - Object.defineProperty(StateService.prototype, "moving$", { + Object.defineProperty(StateService.prototype, "inMotion$", { get: function () { - return this._moving$; + return this._inMotion$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(StateService.prototype, "inTranslation$", { + get: function () { + return this._inTranslation$; }, enumerable: true, configurable: true @@ -30873,117 +42957,643 @@ var StateService = (function () { configurable: true }); StateService.prototype.traverse = function () { - this._movingOperation$.next(true); + this._inMotionOperation$.next(true); this._invokeContextOperation(function (context) { context.traverse(); }); }; - StateService.prototype.wait = function () { - this._invokeContextOperation(function (context) { context.wait(); }); + StateService.prototype.wait = function () { + this._invokeContextOperation(function (context) { context.wait(); }); + }; + StateService.prototype.waitInteractively = function () { + this._invokeContextOperation(function (context) { context.waitInteractively(); }); + }; + StateService.prototype.appendNodes = function (nodes) { + this._invokeContextOperation(function (context) { context.append(nodes); }); + }; + StateService.prototype.prependNodes = function (nodes) { + this._invokeContextOperation(function (context) { context.prepend(nodes); }); + }; + StateService.prototype.removeNodes = function (n) { + this._invokeContextOperation(function (context) { context.remove(n); }); + }; + StateService.prototype.clearNodes = function () { + this._invokeContextOperation(function (context) { context.clear(); }); + }; + StateService.prototype.clearPriorNodes = function () { + this._invokeContextOperation(function (context) { context.clearPrior(); }); + }; + StateService.prototype.cutNodes = function () { + this._invokeContextOperation(function (context) { context.cut(); }); + }; + StateService.prototype.setNodes = function (nodes) { + this._invokeContextOperation(function (context) { context.set(nodes); }); + }; + StateService.prototype.rotate = function (delta) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.rotate(delta); }); + }; + StateService.prototype.rotateBasic = function (basicRotation) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); }); + }; + StateService.prototype.rotateBasicUnbounded = function (basicRotation) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); }); + }; + StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); }); + }; + StateService.prototype.rotateToBasic = function (basic) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.rotateToBasic(basic); }); + }; + StateService.prototype.move = function (delta) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.move(delta); }); + }; + StateService.prototype.moveTo = function (position) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.moveTo(position); }); + }; + /** + * Change zoom level while keeping the reference point position approximately static. + * + * @parameter {number} delta - Change in zoom level. + * @parameter {Array} reference - Reference point in basic coordinates. + */ + StateService.prototype.zoomIn = function (delta, reference) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); }); + }; + StateService.prototype.getCenter = function () { + return this._lastState$ + .first() + .map(function (frame) { + return frame.state.getCenter(); + }); + }; + StateService.prototype.getZoom = function () { + return this._lastState$ + .first() + .map(function (frame) { + return frame.state.zoom; + }); + }; + StateService.prototype.setCenter = function (center) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.setCenter(center); }); + }; + StateService.prototype.setSpeed = function (speed) { + this._invokeContextOperation(function (context) { context.setSpeed(speed); }); + }; + StateService.prototype.setTransitionMode = function (mode) { + this._invokeContextOperation(function (context) { context.setTransitionMode(mode); }); + }; + StateService.prototype.setZoom = function (zoom) { + this._inMotionOperation$.next(true); + this._invokeContextOperation(function (context) { context.setZoom(zoom); }); + }; + StateService.prototype.start = function () { + if (this._frameId == null) { + this._start$.next(null); + this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this)); + this._frame$.next(this._frameId); + } + }; + StateService.prototype.stop = function () { + if (this._frameId != null) { + this._frameGenerator.cancelAnimationFrame(this._frameId); + this._frameId = null; + } + }; + StateService.prototype._invokeContextOperation = function (action) { + this._contextOperation$ + .next(function (context) { + action(context); + return context; + }); + }; + StateService.prototype._frame = function (time) { + this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this)); + this._frame$.next(this._frameId); + }; + return StateService; +}()); +exports.StateService = StateService; + +},{"../State":297,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/util/AnimationFrame":217}],420:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Enumeration for transition mode + * @enum {number} + * @readonly + * @description Modes for specifying how transitions + * between nodes are performed. + */ +var TransitionMode; +(function (TransitionMode) { + /** + * Default transitions. + * + * @description The viewer dynamically determines + * whether transitions should be performed with or + * without motion and blending for each transition + * based on the underlying data. + */ + TransitionMode[TransitionMode["Default"] = 0] = "Default"; + /** + * Instantaneous transitions. + * + * @description All transitions are performed + * without motion or blending. + */ + TransitionMode[TransitionMode["Instantaneous"] = 1] = "Instantaneous"; +})(TransitionMode = exports.TransitionMode || (exports.TransitionMode = {})); +exports.default = TransitionMode; + +},{}],421:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var State_1 = require("../../State"); +var InteractiveStateBase = /** @class */ (function (_super) { + __extends(InteractiveStateBase, _super); + function InteractiveStateBase(state) { + var _this = _super.call(this, state) || this; + _this._animationSpeed = 1 / 40; + _this._rotationDelta = new State_1.RotationDelta(0, 0); + _this._requestedRotationDelta = null; + _this._basicRotation = [0, 0]; + _this._requestedBasicRotation = null; + _this._requestedBasicRotationUnbounded = null; + _this._rotationAcceleration = 0.86; + _this._rotationIncreaseAlpha = 0.97; + _this._rotationDecreaseAlpha = 0.9; + _this._rotationThreshold = 1e-3; + _this._unboundedRotationAlpha = 0.8; + _this._desiredZoom = state.zoom; + _this._minZoom = 0; + _this._maxZoom = 3; + _this._lookatDepth = 10; + _this._desiredLookat = null; + _this._desiredCenter = null; + return _this; + } + InteractiveStateBase.prototype.rotate = function (rotationDelta) { + if (this._currentNode == null) { + return; + } + this._desiredZoom = this._zoom; + this._desiredLookat = null; + this._requestedBasicRotation = null; + if (this._requestedRotationDelta != null) { + this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi; + this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta; + } + else { + this._requestedRotationDelta = new State_1.RotationDelta(rotationDelta.phi, rotationDelta.theta); + } + }; + InteractiveStateBase.prototype.rotateBasic = function (basicRotation) { + if (this._currentNode == null) { + return; + } + this._desiredZoom = this._zoom; + this._desiredLookat = null; + this._requestedRotationDelta = null; + if (this._requestedBasicRotation != null) { + this._requestedBasicRotation[0] += basicRotation[0]; + this._requestedBasicRotation[1] += basicRotation[1]; + var threshold = 0.05 / Math.pow(2, this._zoom); + this._requestedBasicRotation[0] = + this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold); + this._requestedBasicRotation[1] = + this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold); + } + else { + this._requestedBasicRotation = basicRotation.slice(); + } + }; + InteractiveStateBase.prototype.rotateBasicUnbounded = function (basicRotation) { + if (this._currentNode == null) { + return; + } + if (this._requestedBasicRotationUnbounded != null) { + this._requestedBasicRotationUnbounded[0] += basicRotation[0]; + this._requestedBasicRotationUnbounded[1] += basicRotation[1]; + } + else { + this._requestedBasicRotationUnbounded = basicRotation.slice(); + } + }; + InteractiveStateBase.prototype.rotateBasicWithoutInertia = function (basic) { + if (this._currentNode == null) { + return; + } + this._desiredZoom = this._zoom; + this._desiredLookat = null; + this._requestedRotationDelta = null; + this._requestedBasicRotation = null; + var threshold = 0.05 / Math.pow(2, this._zoom); + var basicRotation = basic.slice(); + basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold); + basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold); + this._applyRotationBasic(basicRotation); + }; + InteractiveStateBase.prototype.rotateToBasic = function (basic) { + if (this._currentNode == null) { + return; + } + this._desiredZoom = this._zoom; + this._desiredLookat = null; + basic[0] = this._spatial.clamp(basic[0], 0, 1); + basic[1] = this._spatial.clamp(basic[1], 0, 1); + var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth); + this._currentCamera.lookat.fromArray(lookat); + }; + InteractiveStateBase.prototype.zoomIn = function (delta, reference) { + if (this._currentNode == null) { + return; + } + this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta)); + var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray()); + var currentCenterX = currentCenter[0]; + var currentCenterY = currentCenter[1]; + var zoom0 = Math.pow(2, this._zoom); + var zoom1 = Math.pow(2, this._desiredZoom); + var refX = reference[0]; + var refY = reference[1]; + if (this.currentTransform.gpano != null && + this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) { + if (refX - currentCenterX > 0.5) { + refX = refX - 1; + } + else if (currentCenterX - refX > 0.5) { + refX = 1 + refX; + } + } + var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX); + var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY); + var gpano = this.currentTransform.gpano; + if (this._currentNode.fullPano) { + newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1); + newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95); + } + else if (gpano != null && + this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) { + newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1); + newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1); + } + else { + newCenterX = this._spatial.clamp(newCenterX, 0, 1); + newCenterY = this._spatial.clamp(newCenterY, 0, 1); + } + this._desiredLookat = new THREE.Vector3() + .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth)); + }; + InteractiveStateBase.prototype.setCenter = function (center) { + this._desiredLookat = null; + this._requestedRotationDelta = null; + this._requestedBasicRotation = null; + this._desiredZoom = this._zoom; + var clamped = [ + this._spatial.clamp(center[0], 0, 1), + this._spatial.clamp(center[1], 0, 1), + ]; + if (this._currentNode == null) { + this._desiredCenter = clamped; + return; + } + this._desiredCenter = null; + var currentLookat = new THREE.Vector3() + .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth)); + var previousTransform = this.previousTransform != null ? + this.previousTransform : + this.currentTransform; + var previousLookat = new THREE.Vector3() + .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth)); + this._currentCamera.lookat.copy(currentLookat); + this._previousCamera.lookat.copy(previousLookat); }; - StateService.prototype.appendNodes = function (nodes) { - this._invokeContextOperation(function (context) { context.append(nodes); }); + InteractiveStateBase.prototype.setZoom = function (zoom) { + this._desiredLookat = null; + this._requestedRotationDelta = null; + this._requestedBasicRotation = null; + this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom); + this._desiredZoom = this._zoom; }; - StateService.prototype.prependNodes = function (nodes) { - this._invokeContextOperation(function (context) { context.prepend(nodes); }); + InteractiveStateBase.prototype._applyRotation = function (camera) { + if (camera == null) { + return; + } + var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1)); + var qInverse = q.clone().inverse(); + var offset = new THREE.Vector3(); + offset.copy(camera.lookat).sub(camera.position); + offset.applyQuaternion(q); + var length = offset.length(); + var phi = Math.atan2(offset.y, offset.x); + phi += this._rotationDelta.phi; + var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z); + theta += this._rotationDelta.theta; + theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta)); + offset.x = Math.sin(theta) * Math.cos(phi); + offset.y = Math.sin(theta) * Math.sin(phi); + offset.z = Math.cos(theta); + offset.applyQuaternion(qInverse); + camera.lookat.copy(camera.position).add(offset.multiplyScalar(length)); }; - StateService.prototype.removeNodes = function (n) { - this._invokeContextOperation(function (context) { context.remove(n); }); + InteractiveStateBase.prototype._applyRotationBasic = function (basicRotation) { + var currentNode = this._currentNode; + var previousNode = this._previousNode != null ? + this.previousNode : + this.currentNode; + var currentCamera = this._currentCamera; + var previousCamera = this._previousCamera; + var currentTransform = this.currentTransform; + var previousTransform = this.previousTransform != null ? + this.previousTransform : + this.currentTransform; + var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray()); + var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray()); + var currentGPano = currentTransform.gpano; + var previousGPano = previousTransform.gpano; + if (currentNode.fullPano) { + currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1); + currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95); + } + else if (currentGPano != null && + currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) { + currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1); + currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1); + } + else { + currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1); + currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1); + } + if (previousNode.fullPano) { + previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1); + previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95); + } + else if (previousGPano != null && + previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) { + previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1); + previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1); + } + else { + previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1); + previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1); + } + var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth); + currentCamera.lookat.fromArray(currentLookat); + var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth); + previousCamera.lookat.fromArray(previousLookat); }; - StateService.prototype.cutNodes = function () { - this._invokeContextOperation(function (context) { context.cut(); }); + InteractiveStateBase.prototype._updateZoom = function (animationSpeed) { + var diff = this._desiredZoom - this._zoom; + var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0; + if (diff === 0) { + return; + } + else if (Math.abs(diff) < 2e-3) { + this._zoom = this._desiredZoom; + if (this._desiredLookat != null) { + this._desiredLookat = null; + } + } + else { + this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3); + } }; - StateService.prototype.setNodes = function (nodes) { - this._invokeContextOperation(function (context) { context.set(nodes); }); + InteractiveStateBase.prototype._updateLookat = function (animationSpeed) { + if (this._desiredLookat === null) { + return; + } + var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat); + if (Math.abs(diff) < 1e-6) { + this._currentCamera.lookat.copy(this._desiredLookat); + this._desiredLookat = null; + } + else { + this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed); + } }; - StateService.prototype.rotate = function (delta) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.rotate(delta); }); + InteractiveStateBase.prototype._updateRotation = function () { + if (this._requestedRotationDelta != null) { + var length_1 = this._rotationDelta.lengthSquared(); + var requestedLength = this._requestedRotationDelta.lengthSquared(); + if (requestedLength > length_1) { + this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha); + } + else { + this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha); + } + this._requestedRotationDelta = null; + return; + } + if (this._rotationDelta.isZero) { + return; + } + this._rotationDelta.multiply(this._rotationAcceleration); + this._rotationDelta.threshold(this._rotationThreshold); }; - StateService.prototype.rotateBasic = function (basicRotation) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); }); + InteractiveStateBase.prototype._updateRotationBasic = function () { + if (this._requestedBasicRotation != null) { + var x = this._basicRotation[0]; + var y = this._basicRotation[1]; + var reqX = this._requestedBasicRotation[0]; + var reqY = this._requestedBasicRotation[1]; + if (Math.abs(reqX) > Math.abs(x)) { + this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX; + } + else { + this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX; + } + if (Math.abs(reqY) > Math.abs(y)) { + this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY; + } + else { + this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY; + } + this._requestedBasicRotation = null; + return; + } + if (this._requestedBasicRotationUnbounded != null) { + var reqX = this._requestedBasicRotationUnbounded[0]; + var reqY = this._requestedBasicRotationUnbounded[1]; + if (Math.abs(reqX) > 0) { + this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX; + } + if (Math.abs(reqY) > 0) { + this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY; + } + if (this._desiredLookat != null) { + var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray()); + desiredBasicLookat[0] += reqX; + desiredBasicLookat[1] += reqY; + this._desiredLookat = new THREE.Vector3() + .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth)); + } + this._requestedBasicRotationUnbounded = null; + } + if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) { + return; + } + this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0]; + this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1]; + if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) && + Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) { + this._basicRotation = [0, 0]; + } }; - StateService.prototype.rotateToBasic = function (basic) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.rotateToBasic(basic); }); + InteractiveStateBase.prototype._clearRotation = function () { + if (this._currentNode.fullPano) { + return; + } + if (this._requestedRotationDelta != null) { + this._requestedRotationDelta = null; + } + if (!this._rotationDelta.isZero) { + this._rotationDelta.reset(); + } + if (this._requestedBasicRotation != null) { + this._requestedBasicRotation = null; + } + if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) { + this._basicRotation = [0, 0]; + } }; - StateService.prototype.move = function (delta) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.move(delta); }); + InteractiveStateBase.prototype._setDesiredCenter = function () { + if (this._desiredCenter == null) { + return; + } + var lookatDirection = new THREE.Vector3() + .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth)) + .sub(this._currentCamera.position); + this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection)); + this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection)); + this._desiredCenter = null; }; - StateService.prototype.moveTo = function (position) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.moveTo(position); }); + InteractiveStateBase.prototype._setDesiredZoom = function () { + this._desiredZoom = + this._currentNode.fullPano || this._previousNode == null ? + this._zoom : 0; }; - /** - * Change zoom level while keeping the reference point position approximately static. - * - * @parameter {number} delta - Change in zoom level. - * @parameter {Array} reference - Reference point in basic coordinates. - */ - StateService.prototype.zoomIn = function (delta, reference) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); }); + return InteractiveStateBase; +}(State_1.StateBase)); +exports.InteractiveStateBase = InteractiveStateBase; +exports.default = InteractiveStateBase; + +},{"../../State":297,"three":240}],422:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - StateService.prototype.getCenter = function () { - return this._lastState$ - .first() - .map(function (frame) { - return frame.state.getCenter(); - }); +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var State_1 = require("../../State"); +var InteractiveWaitingState = /** @class */ (function (_super) { + __extends(InteractiveWaitingState, _super); + function InteractiveWaitingState(state) { + var _this = _super.call(this, state) || this; + _this._adjustCameras(); + _this._motionless = _this._motionlessTransition(); + return _this; + } + InteractiveWaitingState.prototype.traverse = function () { + return new State_1.TraversingState(this); }; - StateService.prototype.getZoom = function () { - return this._lastState$ - .first() - .map(function (frame) { - return frame.state.zoom; - }); + InteractiveWaitingState.prototype.wait = function () { + return new State_1.WaitingState(this); }; - StateService.prototype.setCenter = function (center) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.setCenter(center); }); + InteractiveWaitingState.prototype.waitInteractively = function () { + throw new Error("Not implemented"); }; - StateService.prototype.setZoom = function (zoom) { - this._movingOperation$.next(true); - this._invokeContextOperation(function (context) { context.setZoom(zoom); }); + InteractiveWaitingState.prototype.prepend = function (nodes) { + _super.prototype.prepend.call(this, nodes); + this._motionless = this._motionlessTransition(); + }; + InteractiveWaitingState.prototype.set = function (nodes) { + _super.prototype.set.call(this, nodes); + this._motionless = this._motionlessTransition(); + }; + InteractiveWaitingState.prototype.setSpeed = function (speed) { return; }; + InteractiveWaitingState.prototype.move = function (delta) { + this._alpha = Math.max(0, Math.min(1, this._alpha + delta)); + }; + InteractiveWaitingState.prototype.moveTo = function (position) { + this._alpha = Math.max(0, Math.min(1, position)); }; - StateService.prototype.start = function () { - if (this._frameId == null) { - this._start$.next(null); - this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this)); - this._frame$.next(this._frameId); + InteractiveWaitingState.prototype.update = function (fps) { + this._updateRotation(); + if (!this._rotationDelta.isZero) { + this._applyRotation(this._previousCamera); + this._applyRotation(this._currentCamera); } - }; - StateService.prototype.stop = function () { - if (this._frameId != null) { - this._frameGenerator.cancelAnimationFrame(this._frameId); - this._frameId = null; + this._updateRotationBasic(); + if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) { + this._applyRotationBasic(this._basicRotation); } + var animationSpeed = this._animationSpeed * (60 / fps); + this._updateZoom(animationSpeed); + this._updateLookat(animationSpeed); + this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha); }; - StateService.prototype._invokeContextOperation = function (action) { - this._contextOperation$ - .next(function (context) { - action(context); - return context; - }); + InteractiveWaitingState.prototype._getAlpha = function () { + return this._motionless ? Math.round(this._alpha) : this._alpha; }; - StateService.prototype._frame = function (time) { - this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this)); - this._frame$.next(this._frameId); + InteractiveWaitingState.prototype._setCurrentCamera = function () { + _super.prototype._setCurrentCamera.call(this); + this._adjustCameras(); }; - return StateService; -}()); -exports.StateService = StateService; + InteractiveWaitingState.prototype._adjustCameras = function () { + if (this._previousNode == null) { + return; + } + if (this._currentNode.fullPano) { + var lookat = this._camera.lookat.clone().sub(this._camera.position); + this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position)); + } + if (this._previousNode.fullPano) { + var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position); + this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position)); + } + }; + return InteractiveWaitingState; +}(State_1.InteractiveStateBase)); +exports.InteractiveWaitingState = InteractiveWaitingState; +exports.default = InteractiveWaitingState; -},{"../State":214,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/do":54,"rxjs/add/operator/filter":56,"rxjs/add/operator/first":58,"rxjs/add/operator/map":60,"rxjs/add/operator/pairwise":64,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/startWith":72,"rxjs/add/operator/switchMap":73,"rxjs/add/operator/withLatestFrom":76}],304:[function(require,module,exports){ -/// +},{"../../State":297}],423:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var Error_1 = require("../../Error"); var Geo_1 = require("../../Geo"); -var StateBase = (function () { +var State_1 = require("../../State"); +var StateBase = /** @class */ (function () { function StateBase(state) { this._spatial = new Geo_1.Spatial(); this._geoCoords = new Geo_1.GeoCoords(); this._referenceThreshold = 0.01; + this._transitionMode = state.transitionMode; this._reference = state.reference; this._alpha = state.alpha; this._camera = state.camera.clone(); @@ -30995,7 +43605,7 @@ var StateBase = (function () { for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) { var node = _a[_i]; var translation = this._nodeToTranslation(node); - var transform = new Geo_1.Transform(node, node.image, translation); + var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image); this._trajectoryTransforms.push(transform); this._trajectoryCameras.push(new Geo_1.Camera(transform)); } @@ -31098,6 +43708,13 @@ var StateBase = (function () { enumerable: true, configurable: true }); + Object.defineProperty(StateBase.prototype, "transitionMode", { + get: function () { + return this._transitionMode; + }, + enumerable: true, + configurable: true + }); StateBase.prototype.append = function (nodes) { if (nodes.length < 1) { throw Error("Trajectory can not be empty"); @@ -31130,14 +43747,26 @@ var StateBase = (function () { if (n < 0) { throw Error("n must be a positive integer"); } - var length = this._trajectory.length; - if (length - (this._currentIndex + 1) < n) { - throw Error("Current node can not be removed"); + if (this._currentIndex - 1 < n) { + throw Error("Current and previous nodes can not be removed"); } for (var i = 0; i < n; i++) { - this._trajectory.pop(); - this._trajectoryTransforms.pop(); - this._trajectoryCameras.pop(); + this._trajectory.shift(); + this._trajectoryTransforms.shift(); + this._trajectoryCameras.shift(); + this._currentIndex--; + } + this._setCurrentNode(); + }; + StateBase.prototype.clearPrior = function () { + if (this._currentIndex > 0) { + this.remove(this._currentIndex - 1); + } + }; + StateBase.prototype.clear = function () { + this.cut(); + if (this._currentIndex > 0) { + this.remove(this._currentIndex - 1); } }; StateBase.prototype.cut = function () { @@ -31159,6 +43788,9 @@ var StateBase = (function () { this.currentTransform.projectBasic(this._camera.lookat.toArray()) : [0.5, 0.5]; }; + StateBase.prototype.setTransitionMode = function (mode) { + this._transitionMode = mode; + }; StateBase.prototype._setCurrent = function () { this._setCurrentNode(); var referenceReset = this._setReference(this._currentNode); @@ -31175,10 +43807,10 @@ var StateBase = (function () { }; StateBase.prototype._motionlessTransition = function () { var nodesSet = this._currentNode != null && this._previousNode != null; - return nodesSet && !(this._currentNode.merged && + return nodesSet && (this._transitionMode === State_1.TransitionMode.Instantaneous || !(this._currentNode.merged && this._previousNode.merged && this._withinOriginalDistance() && - this._sameConnectedComponent()); + this._sameConnectedComponent())); }; StateBase.prototype._setReference = function (node) { // do not reset reference if node is within threshold distance @@ -31205,7 +43837,7 @@ var StateBase = (function () { }; StateBase.prototype._setTrajectory = function (nodes) { if (nodes.length < 1) { - throw new Error_1.ParameterMapillaryError("Trajectory can not be empty"); + throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty"); } if (this._currentNode != null) { this._trajectory = [this._currentNode].concat(nodes); @@ -31225,10 +43857,10 @@ var StateBase = (function () { for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { var node = nodes_1[_i]; if (!node.assetsCached) { - throw new Error_1.ParameterMapillaryError("Assets must be cached when node is added to trajectory"); + throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory"); } var translation = this._nodeToTranslation(node); - var transform = new Geo_1.Transform(node, node.image, translation); + var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image); this._trajectoryTransforms.push(transform); this._trajectoryCameras.push(new Geo_1.Camera(transform)); } @@ -31237,10 +43869,10 @@ var StateBase = (function () { for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) { var node = _a[_i]; if (!node.assetsCached) { - throw new Error_1.ParameterMapillaryError("Node must be loaded when added to trajectory"); + throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory"); } var translation = this._nodeToTranslation(node); - var transform = new Geo_1.Transform(node, node.image, translation); + var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image); this._trajectoryTransforms.unshift(transform); this._trajectoryCameras.unshift(new Geo_1.Camera(transform)); } @@ -31253,13 +43885,8 @@ var StateBase = (function () { StateBase.prototype._sameConnectedComponent = function () { var current = this._currentNode; var previous = this._previousNode; - if (!current || - !current.mergeCC || - !previous || - !previous.mergeCC) { - return true; - } - return current.mergeCC === previous.mergeCC; + return !!current && !!previous && + current.mergeCC === previous.mergeCC; }; StateBase.prototype._withinOriginalDistance = function () { var current = this._currentNode; @@ -31275,97 +43902,33 @@ var StateBase = (function () { }()); exports.StateBase = StateBase; -},{"../../Error":209,"../../Geo":210}],305:[function(require,module,exports){ -/// +},{"../../Error":292,"../../Geo":293,"../../State":297}],424:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var THREE = require("three"); -var UnitBezier = require("unitbezier"); -var State_1 = require("../../State"); -var RotationDelta = (function () { - function RotationDelta(phi, theta) { - this._phi = phi; - this._theta = theta; - } - Object.defineProperty(RotationDelta.prototype, "phi", { - get: function () { - return this._phi; - }, - set: function (value) { - this._phi = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(RotationDelta.prototype, "theta", { - get: function () { - return this._theta; - }, - set: function (value) { - this._theta = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(RotationDelta.prototype, "isZero", { - get: function () { - return this._phi === 0 && this._theta === 0; - }, - enumerable: true, - configurable: true - }); - RotationDelta.prototype.copy = function (delta) { - this._phi = delta.phi; - this._theta = delta.theta; - }; - RotationDelta.prototype.lerp = function (other, alpha) { - this._phi = (1 - alpha) * this._phi + alpha * other.phi; - this._theta = (1 - alpha) * this._theta + alpha * other.theta; - }; - RotationDelta.prototype.multiply = function (value) { - this._phi *= value; - this._theta *= value; - }; - RotationDelta.prototype.threshold = function (value) { - this._phi = Math.abs(this._phi) > value ? this._phi : 0; - this._theta = Math.abs(this._theta) > value ? this._theta : 0; - }; - RotationDelta.prototype.lengthSquared = function () { - return this._phi * this._phi + this._theta * this._theta; - }; - RotationDelta.prototype.reset = function () { - this._phi = 0; - this._theta = 0; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - return RotationDelta; -}()); -var TraversingState = (function (_super) { +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var UnitBezier = require("@mapbox/unitbezier"); +var State_1 = require("../../State"); +var TraversingState = /** @class */ (function (_super) { __extends(TraversingState, _super); function TraversingState(state) { - _super.call(this, state); - this._motionless = this._motionlessTransition(); - this._baseAlpha = this._alpha; - this._animationSpeed = 0.025; - this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96); - this._useBezier = false; - this._rotationDelta = new RotationDelta(0, 0); - this._requestedRotationDelta = null; - this._basicRotation = [0, 0]; - this._requestedBasicRotation = null; - this._rotationAcceleration = 0.86; - this._rotationIncreaseAlpha = 0.97; - this._rotationDecreaseAlpha = 0.9; - this._rotationThreshold = 0.001; - this._desiredZoom = state.zoom; - this._minZoom = 0; - this._maxZoom = 3; - this._lookatDepth = 10; - this._desiredLookat = null; - this._desiredCenter = null; + var _this = _super.call(this, state) || this; + _this._adjustCameras(); + _this._motionless = _this._motionlessTransition(); + _this._baseAlpha = _this._alpha; + _this._speedCoefficient = 1; + _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96); + _this._useBezier = false; + return _this; } TraversingState.prototype.traverse = function () { throw new Error("Not implemented"); @@ -31373,6 +43936,9 @@ var TraversingState = (function (_super) { TraversingState.prototype.wait = function () { return new State_1.WaitingState(this); }; + TraversingState.prototype.waitInteractively = function () { + return new State_1.InteractiveWaitingState(this); + }; TraversingState.prototype.append = function (nodes) { var emptyTrajectory = this._trajectory.length === 0; if (emptyTrajectory) { @@ -31388,141 +43954,32 @@ var TraversingState = (function (_super) { var emptyTrajectory = this._trajectory.length === 0; if (emptyTrajectory) { this._resetTransition(); - } - _super.prototype.prepend.call(this, nodes); - if (emptyTrajectory) { - this._setDesiredCenter(); - this._setDesiredZoom(); - } - }; - TraversingState.prototype.set = function (nodes) { - _super.prototype.set.call(this, nodes); - this._desiredLookat = null; - this._resetTransition(); - this._clearRotation(); - this._setDesiredCenter(); - this._setDesiredZoom(); - if (this._trajectory.length < 3) { - this._useBezier = true; - } - }; - TraversingState.prototype.move = function (delta) { - throw new Error("Not implemented"); - }; - TraversingState.prototype.moveTo = function (delta) { - throw new Error("Not implemented"); - }; - TraversingState.prototype.rotate = function (rotationDelta) { - if (this._currentNode == null) { - return; - } - this._desiredZoom = this._zoom; - this._desiredLookat = null; - this._requestedBasicRotation = null; - if (this._requestedRotationDelta != null) { - this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi; - this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta; - } - else { - this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta); - } - }; - TraversingState.prototype.rotateBasic = function (basicRotation) { - if (this._currentNode == null) { - return; - } - this._desiredZoom = this._zoom; - this._desiredLookat = null; - this._requestedRotationDelta = null; - if (this._requestedBasicRotation != null) { - this._requestedBasicRotation[0] += basicRotation[0]; - this._requestedBasicRotation[1] += basicRotation[1]; - } - else { - this._requestedBasicRotation = basicRotation.slice(); - } - }; - TraversingState.prototype.rotateToBasic = function (basic) { - if (this._currentNode == null) { - return; - } - this._desiredZoom = this._zoom; - this._desiredLookat = null; - basic[0] = this._spatial.clamp(basic[0], 0, 1); - basic[1] = this._spatial.clamp(basic[1], 0, 1); - var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth); - this._currentCamera.lookat.fromArray(lookat); - }; - TraversingState.prototype.zoomIn = function (delta, reference) { - if (this._currentNode == null) { - return; - } - this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta)); - var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray()); - var currentCenterX = currentCenter[0]; - var currentCenterY = currentCenter[1]; - var zoom0 = Math.pow(2, this._zoom); - var zoom1 = Math.pow(2, this._desiredZoom); - var refX = reference[0]; - var refY = reference[1]; - if (this.currentTransform.gpano != null && - this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) { - if (refX - currentCenterX > 0.5) { - refX = refX - 1; - } - else if (currentCenterX - refX > 0.5) { - refX = 1 + refX; - } - } - var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX); - var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY); - var gpano = this.currentTransform.gpano; - if (this._currentNode.fullPano) { - newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1); - newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95); - } - else if (gpano != null && - this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) { - newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1); - newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1); - } - else { - newCenterX = this._spatial.clamp(newCenterX, 0, 1); - newCenterY = this._spatial.clamp(newCenterY, 0, 1); - } - this._desiredLookat = new THREE.Vector3() - .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth)); - }; - TraversingState.prototype.setCenter = function (center) { - this._desiredLookat = null; - this._requestedRotationDelta = null; - this._requestedBasicRotation = null; - this._desiredZoom = this._zoom; - var clamped = [ - this._spatial.clamp(center[0], 0, 1), - this._spatial.clamp(center[1], 0, 1), - ]; - if (this._currentNode == null) { - this._desiredCenter = clamped; - return; - } - this._desiredCenter = null; - var currentLookat = new THREE.Vector3() - .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth)); - var previousTransform = this.previousTransform != null ? - this.previousTransform : - this.currentTransform; - var previousLookat = new THREE.Vector3() - .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth)); - this._currentCamera.lookat.copy(currentLookat); - this._previousCamera.lookat.copy(previousLookat); + } + _super.prototype.prepend.call(this, nodes); + if (emptyTrajectory) { + this._setDesiredCenter(); + this._setDesiredZoom(); + } }; - TraversingState.prototype.setZoom = function (zoom) { + TraversingState.prototype.set = function (nodes) { + _super.prototype.set.call(this, nodes); this._desiredLookat = null; - this._requestedRotationDelta = null; - this._requestedBasicRotation = null; - this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom); - this._desiredZoom = this._zoom; + this._resetTransition(); + this._clearRotation(); + this._setDesiredCenter(); + this._setDesiredZoom(); + if (this._trajectory.length < 3) { + this._useBezier = true; + } + }; + TraversingState.prototype.move = function (delta) { + throw new Error("Not implemented"); + }; + TraversingState.prototype.moveTo = function (delta) { + throw new Error("Not implemented"); + }; + TraversingState.prototype.setSpeed = function (speed) { + this._speedCoefficient = this._spatial.clamp(speed, 0, 10); }; TraversingState.prototype.update = function (fps) { if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) { @@ -31536,7 +43993,7 @@ var TraversingState = (function (_super) { this._desiredLookat = null; } var animationSpeed = this._animationSpeed * (60 / fps); - this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed); + this._baseAlpha = Math.min(1, this._baseAlpha + this._speedCoefficient * animationSpeed); if (this._useBezier) { this._alpha = this._unitBezier.solve(this._baseAlpha); } @@ -31550,7 +44007,7 @@ var TraversingState = (function (_super) { } this._updateRotationBasic(); if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) { - this._applyRotationBasic(); + this._applyRotationBasic(this._basicRotation); } this._updateZoom(animationSpeed); this._updateLookat(animationSpeed); @@ -31561,263 +44018,926 @@ var TraversingState = (function (_super) { }; TraversingState.prototype._setCurrentCamera = function () { _super.prototype._setCurrentCamera.call(this); - if (this._previousNode != null) { + this._adjustCameras(); + }; + TraversingState.prototype._adjustCameras = function () { + if (this._previousNode == null) { + return; + } + var lookat = this._camera.lookat.clone().sub(this._camera.position); + this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position)); + if (this._currentNode.fullPano) { + this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position)); + } + }; + TraversingState.prototype._resetTransition = function () { + this._alpha = 0; + this._baseAlpha = 0; + this._motionless = this._motionlessTransition(); + }; + return TraversingState; +}(State_1.InteractiveStateBase)); +exports.TraversingState = TraversingState; +exports.default = TraversingState; + +},{"../../State":297,"@mapbox/unitbezier":2}],425:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var State_1 = require("../../State"); +var WaitingState = /** @class */ (function (_super) { + __extends(WaitingState, _super); + function WaitingState(state) { + var _this = _super.call(this, state) || this; + _this._zoom = 0; + _this._adjustCameras(); + _this._motionless = _this._motionlessTransition(); + return _this; + } + WaitingState.prototype.traverse = function () { + return new State_1.TraversingState(this); + }; + WaitingState.prototype.wait = function () { + throw new Error("Not implemented"); + }; + WaitingState.prototype.waitInteractively = function () { + return new State_1.InteractiveWaitingState(this); + }; + WaitingState.prototype.prepend = function (nodes) { + _super.prototype.prepend.call(this, nodes); + this._motionless = this._motionlessTransition(); + }; + WaitingState.prototype.set = function (nodes) { + _super.prototype.set.call(this, nodes); + this._motionless = this._motionlessTransition(); + }; + WaitingState.prototype.rotate = function (delta) { return; }; + WaitingState.prototype.rotateBasic = function (basicRotation) { return; }; + WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; }; + WaitingState.prototype.rotateBasicWithoutInertia = function (basicRotation) { return; }; + WaitingState.prototype.rotateToBasic = function (basic) { return; }; + WaitingState.prototype.setSpeed = function (speed) { return; }; + WaitingState.prototype.zoomIn = function (delta, reference) { return; }; + WaitingState.prototype.move = function (delta) { + this._alpha = Math.max(0, Math.min(1, this._alpha + delta)); + }; + WaitingState.prototype.moveTo = function (position) { + this._alpha = Math.max(0, Math.min(1, position)); + }; + WaitingState.prototype.update = function (fps) { + this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha); + }; + WaitingState.prototype.setCenter = function (center) { return; }; + WaitingState.prototype.setZoom = function (zoom) { return; }; + WaitingState.prototype._getAlpha = function () { + return this._motionless ? Math.round(this._alpha) : this._alpha; + }; + WaitingState.prototype._setCurrentCamera = function () { + _super.prototype._setCurrentCamera.call(this); + this._adjustCameras(); + }; + WaitingState.prototype._adjustCameras = function () { + if (this._previousNode == null) { + return; + } + if (this._currentNode.fullPano) { var lookat = this._camera.lookat.clone().sub(this._camera.position); + this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position)); + } + if (this._previousNode.fullPano) { + var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position); this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position)); - if (this._currentNode.fullPano) { - this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position)); + } + }; + return WaitingState; +}(State_1.StateBase)); +exports.WaitingState = WaitingState; +exports.default = WaitingState; + +},{"../../State":297}],426:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +/** + * @class ImageTileLoader + * + * @classdesc Represents a loader of image tiles. + */ +var ImageTileLoader = /** @class */ (function () { + /** + * Create a new node image tile loader instance. + * + * @param {string} scheme - The URI scheme. + * @param {string} host - The URI host. + * @param {string} [origin] - The origin query param. + */ + function ImageTileLoader(scheme, host, origin) { + this._scheme = scheme; + this._host = host; + this._origin = origin != null ? "?origin=" + origin : ""; + } + /** + * Retrieve an image tile. + * + * @description Retrieve an image tile by specifying the area + * as well as the scaled size. + * + * @param {string} identifier - The identifier of the image. + * @param {number} x - The top left x pixel coordinate for the tile + * in the original image. + * @param {number} y - The top left y pixel coordinate for the tile + * in the original image. + * @param {number} w - The pixel width of the tile in the original image. + * @param {number} h - The pixel height of the tile in the original image. + * @param {number} scaledW - The scaled width of the returned tile. + * @param {number} scaledH - The scaled height of the returned tile. + */ + ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) { + var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg"; + var url = this._scheme + + "://" + + this._host + + characteristics + + this._origin; + var xmlHTTP = null; + return [Observable_1.Observable.create(function (subscriber) { + xmlHTTP = new XMLHttpRequest(); + xmlHTTP.open("GET", url, true); + xmlHTTP.responseType = "arraybuffer"; + xmlHTTP.timeout = 15000; + xmlHTTP.onload = function (event) { + if (xmlHTTP.status !== 200) { + subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " + + ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText))); + return; + } + var image = new Image(); + image.crossOrigin = "Anonymous"; + image.onload = function (e) { + subscriber.next(image); + subscriber.complete(); + }; + image.onerror = function (error) { + subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")")); + }; + var blob = new Blob([xmlHTTP.response]); + image.src = window.URL.createObjectURL(blob); + }; + xmlHTTP.onerror = function (error) { + subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")")); + }; + xmlHTTP.ontimeout = function (error) { + subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")")); + }; + xmlHTTP.onabort = function (event) { + subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")")); + }; + xmlHTTP.send(null); + }), + function () { + if (xmlHTTP != null) { + xmlHTTP.abort(); + } + }, + ]; + }; + return ImageTileLoader; +}()); +exports.ImageTileLoader = ImageTileLoader; +exports.default = ImageTileLoader; + +},{"rxjs/Observable":29}],427:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * @class ImageTileStore + * + * @classdesc Represents a store for image tiles. + */ +var ImageTileStore = /** @class */ (function () { + /** + * Create a new node image tile store instance. + */ + function ImageTileStore() { + this._images = {}; + } + /** + * Add an image tile to the store. + * + * @param {HTMLImageElement} image - The image tile. + * @param {string} key - The identifier for the tile. + * @param {number} level - The level of the tile. + */ + ImageTileStore.prototype.addImage = function (image, key, level) { + if (!(level in this._images)) { + this._images[level] = {}; + } + this._images[level][key] = image; + }; + /** + * Dispose the store. + * + * @description Disposes all cached assets. + */ + ImageTileStore.prototype.dispose = function () { + for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) { + var level = _a[_i]; + var levelImages = this._images[level]; + for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) { + var key = _c[_b]; + window.URL.revokeObjectURL(levelImages[key].src); + delete levelImages[key]; + } + delete this._images[level]; + } + }; + /** + * Get an image tile from the store. + * + * @param {string} key - The identifier for the tile. + * @param {number} level - The level of the tile. + */ + ImageTileStore.prototype.getImage = function (key, level) { + return this._images[level][key]; + }; + /** + * Check if an image tile exist in the store. + * + * @param {string} key - The identifier for the tile. + * @param {number} level - The level of the tile. + */ + ImageTileStore.prototype.hasImage = function (key, level) { + return level in this._images && key in this._images[level]; + }; + return ImageTileStore; +}()); +exports.ImageTileStore = ImageTileStore; +exports.default = ImageTileStore; + +},{}],428:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var Geo_1 = require("../Geo"); +/** + * @class RegionOfInterestCalculator + * + * @classdesc Represents a calculator for regions of interest. + */ +var RegionOfInterestCalculator = /** @class */ (function () { + function RegionOfInterestCalculator() { + this._viewportCoords = new Geo_1.ViewportCoords(); + } + /** + * Compute a region of interest based on the current render camera + * and the viewport size. + * + * @param {RenderCamera} renderCamera - Render camera used for unprojections. + * @param {ISize} size - Viewport size in pixels. + * @param {Transform} transform - Transform used for projections. + * + * @returns {IRegionOfInterest} A region of interest. + */ + RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) { + var viewportBoundaryPoints = this._viewportBoundaryPoints(4); + var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform); + this._clipBoundingBox(bbox); + var viewportPixelWidth = 2 / size.width; + var viewportPixelHeight = 2 / size.height; + var centralViewportPixel = [ + [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight], + [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight], + [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight], + [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight], + ]; + var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform); + return { + bbox: bbox, + pixelHeight: cpbox.maxY - cpbox.minY, + pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1), + }; + }; + RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) { + var points = []; + var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]]; + var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]]; + for (var side = 0; side < 4; ++side) { + var o = os[side]; + var d = ds[side]; + for (var i = 0; i < pointsPerSide; ++i) { + points.push([o[0] + d[0] * i / pointsPerSide, + o[1] + d[1] * i / pointsPerSide]); + } + } + return points; + }; + RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) { + var _this = this; + var basicPoints = viewportPoints + .map(function (point) { + return _this._viewportCoords + .viewportToBasic(point[0], point[1], transform, renderCamera.perspective); + }); + if (transform.gpano != null) { + return this._boundingBoxPano(basicPoints); + } + else { + return this._boundingBox(basicPoints); + } + }; + RegionOfInterestCalculator.prototype._boundingBox = function (points) { + var bbox = { + maxX: Number.NEGATIVE_INFINITY, + maxY: Number.NEGATIVE_INFINITY, + minX: Number.POSITIVE_INFINITY, + minY: Number.POSITIVE_INFINITY, + }; + for (var i = 0; i < points.length; ++i) { + bbox.minX = Math.min(bbox.minX, points[i][0]); + bbox.maxX = Math.max(bbox.maxX, points[i][0]); + bbox.minY = Math.min(bbox.minY, points[i][1]); + bbox.maxY = Math.max(bbox.maxY, points[i][1]); + } + return bbox; + }; + RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) { + var _this = this; + var xs = []; + var ys = []; + for (var i = 0; i < points.length; ++i) { + xs.push(points[i][0]); + ys.push(points[i][1]); + } + xs.sort(function (a, b) { return _this._sign(a - b); }); + ys.sort(function (a, b) { return _this._sign(a - b); }); + var intervalX = this._intervalPano(xs); + return { + maxX: intervalX[1], + maxY: ys[ys.length - 1], + minX: intervalX[0], + minY: ys[0], + }; + }; + /** + * Find the max interval between consecutive numbers. + * Assumes numbers are between 0 and 1, sorted and that + * x is equivalent to x + 1. + */ + RegionOfInterestCalculator.prototype._intervalPano = function (xs) { + var maxdx = 0; + var maxi = -1; + for (var i = 0; i < xs.length - 1; ++i) { + var dx = xs[i + 1] - xs[i]; + if (dx > maxdx) { + maxdx = dx; + maxi = i; + } + } + var loopdx = xs[0] + 1 - xs[xs.length - 1]; + if (loopdx > maxdx) { + return [xs[0], xs[xs.length - 1]]; + } + else { + return [xs[maxi + 1], xs[maxi]]; + } + }; + RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) { + bbox.minX = Math.max(0, Math.min(1, bbox.minX)); + bbox.maxX = Math.max(0, Math.min(1, bbox.maxX)); + bbox.minY = Math.max(0, Math.min(1, bbox.minY)); + bbox.maxY = Math.max(0, Math.min(1, bbox.maxY)); + }; + RegionOfInterestCalculator.prototype._sign = function (n) { + return n > 0 ? 1 : n < 0 ? -1 : 0; + }; + return RegionOfInterestCalculator; +}()); +exports.RegionOfInterestCalculator = RegionOfInterestCalculator; +exports.default = RegionOfInterestCalculator; + +},{"../Geo":293}],429:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var THREE = require("three"); +var Subject_1 = require("rxjs/Subject"); +/** + * @class TextureProvider + * + * @classdesc Represents a provider of textures. + */ +var TextureProvider = /** @class */ (function () { + /** + * Create a new node texture provider instance. + * + * @param {string} key - The identifier of the image for which to request tiles. + * @param {number} width - The full width of the original image. + * @param {number} height - The full height of the original image. + * @param {number} tileSize - The size used when requesting tiles. + * @param {HTMLImageElement} background - Image to use as background. + * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles. + * @param {ImageTileStore} imageTileStore - Store for saving tiles. + * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture. + */ + function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) { + this._disposed = false; + this._key = key; + if (width <= 0 || height <= 0) { + console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded."); + } + this._width = width; + this._height = height; + this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2)); + this._currentLevel = -1; + this._tileSize = tileSize; + this._updated$ = new Subject_1.Subject(); + this._createdSubject$ = new Subject_1.Subject(); + this._created$ = this._createdSubject$ + .publishReplay(1) + .refCount(); + this._createdSubscription = this._created$.subscribe(function () { }); + this._hasSubject$ = new Subject_1.Subject(); + this._has$ = this._hasSubject$ + .startWith(false) + .publishReplay(1) + .refCount(); + this._hasSubscription = this._has$.subscribe(function () { }); + this._abortFunctions = []; + this._tileSubscriptions = {}; + this._renderedCurrentLevelTiles = {}; + this._renderedTiles = {}; + this._background = background; + this._camera = null; + this._imageTileLoader = imageTileLoader; + this._imageTileStore = imageTileStore; + this._renderer = renderer; + this._renderTarget = null; + this._roi = null; + } + Object.defineProperty(TextureProvider.prototype, "disposed", { + /** + * Get disposed. + * + * @returns {boolean} Value indicating whether provider has + * been disposed. + */ + get: function () { + return this._disposed; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureProvider.prototype, "hasTexture$", { + /** + * Get hasTexture$. + * + * @returns {Observable} Observable emitting + * values indicating when the existance of a texture + * changes. + */ + get: function () { + return this._has$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureProvider.prototype, "key", { + /** + * Get key. + * + * @returns {boolean} The identifier of the image for + * which to render textures. + */ + get: function () { + return this._key; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureProvider.prototype, "textureUpdated$", { + /** + * Get textureUpdated$. + * + * @returns {Observable} Observable emitting + * values when an existing texture has been updated. + */ + get: function () { + return this._updated$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureProvider.prototype, "textureCreated$", { + /** + * Get textureCreated$. + * + * @returns {Observable} Observable emitting + * values when a new texture has been created. + */ + get: function () { + return this._created$; + }, + enumerable: true, + configurable: true + }); + /** + * Abort all outstanding image tile requests. + */ + TextureProvider.prototype.abort = function () { + for (var key in this._tileSubscriptions) { + if (!this._tileSubscriptions.hasOwnProperty(key)) { + continue; } + this._tileSubscriptions[key].unsubscribe(); } - }; - TraversingState.prototype._resetTransition = function () { - this._alpha = 0; - this._baseAlpha = 0; - this._motionless = this._motionlessTransition(); - }; - TraversingState.prototype._applyRotation = function (camera) { - if (camera == null) { - return; - } - var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1)); - var qInverse = q.clone().inverse(); - var offset = new THREE.Vector3(); - offset.copy(camera.lookat).sub(camera.position); - offset.applyQuaternion(q); - var length = offset.length(); - var phi = Math.atan2(offset.y, offset.x); - phi += this._rotationDelta.phi; - var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z); - theta += this._rotationDelta.theta; - theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta)); - offset.x = Math.sin(theta) * Math.cos(phi); - offset.y = Math.sin(theta) * Math.sin(phi); - offset.z = Math.cos(theta); - offset.applyQuaternion(qInverse); - camera.lookat.copy(camera.position).add(offset.multiplyScalar(length)); - }; - TraversingState.prototype._applyRotationBasic = function () { - var currentNode = this._currentNode; - var previousNode = this._previousNode != null ? - this.previousNode : - this.currentNode; - var currentCamera = this._currentCamera; - var previousCamera = this._previousCamera; - var currentTransform = this.currentTransform; - var previousTransform = this.previousTransform != null ? - this.previousTransform : - this.currentTransform; - var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray()); - var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray()); - var currentGPano = currentTransform.gpano; - var previousGPano = previousTransform.gpano; - if (currentNode.fullPano) { - currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1); - currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95); - } - else if (currentGPano != null && - currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) { - currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1); - currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1); - } - else { - currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1); - currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1); - } - if (previousNode.fullPano) { - previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1); - previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95); - } - else if (previousGPano != null && - previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) { - previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1); - previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1); - } - else { - previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1); - previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1); + this._tileSubscriptions = {}; + for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) { + var abort = _a[_i]; + abort(); } - var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth); - currentCamera.lookat.fromArray(currentLookat); - var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth); - previousCamera.lookat.fromArray(previousLookat); + this._abortFunctions = []; }; - TraversingState.prototype._updateZoom = function (animationSpeed) { - var diff = this._desiredZoom - this._zoom; - if (diff === 0) { + /** + * Dispose the provider. + * + * @description Disposes all cached assets and + * aborts all outstanding image tile requests. + */ + TextureProvider.prototype.dispose = function () { + if (this._disposed) { + console.warn("Texture already disposed (" + this._key + ")"); return; } - else if (Math.abs(diff) < 0.0001) { - this._zoom = this._desiredZoom; - } - else { - this._zoom += 5 * animationSpeed * diff; - } + this.abort(); + if (this._renderTarget != null) { + this._renderTarget.dispose(); + this._renderTarget = null; + } + this._imageTileStore.dispose(); + this._imageTileStore = null; + this._background = null; + this._camera = null; + this._imageTileLoader = null; + this._renderer = null; + this._roi = null; + this._createdSubscription.unsubscribe(); + this._hasSubscription.unsubscribe(); + this._disposed = true; }; - TraversingState.prototype._updateLookat = function (animationSpeed) { - if (this._desiredLookat === null) { + /** + * Set the region of interest. + * + * @description When the region of interest is set the + * the tile level is determined and tiles for the region + * are fetched from the store or the loader and renderedLevel + * to the texture. + * + * @param {IRegionOfInterest} roi - Spatial edges to cache. + */ + TextureProvider.prototype.setRegionOfInterest = function (roi) { + if (this._width <= 0 || this._height <= 0) { return; } - var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat); - if (Math.abs(diff) < 0.00001) { - this._currentCamera.lookat.copy(this._desiredLookat); - this._desiredLookat = null; + this._roi = roi; + var width = 1 / this._roi.pixelWidth; + var height = 1 / this._roi.pixelHeight; + var size = Math.max(height, width); + var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2)))); + if (currentLevel !== this._currentLevel) { + this.abort(); + this._currentLevel = currentLevel; + if (!(this._currentLevel in this._renderedTiles)) { + this._renderedTiles[this._currentLevel] = []; + } + this._renderedCurrentLevelTiles = {}; + for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) { + var tile = _a[_i]; + this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true; + } + } + var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]); + var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]); + var tiles = this._getTiles(topLeft, bottomRight); + if (this._camera == null) { + this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1); + this._camera.position.z = 1; + var gl = this._renderer.getContext(); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var backgroundSize = Math.max(this._width, this._height); + var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize; + var targetWidth = Math.floor(scale * this._width); + var targetHeight = Math.floor(scale * this._height); + this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, { + depthBuffer: false, + format: THREE.RGBFormat, + magFilter: THREE.LinearFilter, + minFilter: THREE.LinearFilter, + stencilBuffer: false, + }); + this._renderToTarget(0, 0, this._width, this._height, this._background); + this._createdSubject$.next(this._renderTarget.texture); + this._hasSubject$.next(true); } - else { - this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed); + this._fetchTiles(tiles); + }; + TextureProvider.prototype.setTileSize = function (tileSize) { + this._tileSize = tileSize; + }; + /** + * Update the image used as background for the texture. + * + * @param {HTMLImageElement} background - The background image. + */ + TextureProvider.prototype.updateBackground = function (background) { + this._background = background; + }; + /** + * Retrieve an image tile. + * + * @description Retrieve an image tile and render it to the + * texture. Add the tile to the store and emit to the updated + * observable. + * + * @param {Array} tile - The tile coordinates. + * @param {number} level - The tile level. + * @param {number} x - The top left x pixel coordinate of the tile. + * @param {number} y - The top left y pixel coordinate of the tile. + * @param {number} w - The pixel width of the tile. + * @param {number} h - The pixel height of the tile. + * @param {number} scaledW - The scaled width of the returned tile. + * @param {number} scaledH - The scaled height of the returned tile. + */ + TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) { + var _this = this; + var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY); + var tile$ = getTile[0]; + var abort = getTile[1]; + this._abortFunctions.push(abort); + var tileKey = this._tileKey(this._tileSize, tile); + var subscription = tile$ + .subscribe(function (image) { + _this._renderToTarget(x, y, w, h, image); + _this._removeFromDictionary(tileKey, _this._tileSubscriptions); + _this._removeFromArray(abort, _this._abortFunctions); + _this._setTileRendered(tile, _this._currentLevel); + _this._imageTileStore.addImage(image, tileKey, level); + _this._updated$.next(true); + }, function (error) { + _this._removeFromDictionary(tileKey, _this._tileSubscriptions); + _this._removeFromArray(abort, _this._abortFunctions); + console.error(error); + }); + if (!subscription.closed) { + this._tileSubscriptions[tileKey] = subscription; } }; - TraversingState.prototype._updateRotation = function () { - if (this._requestedRotationDelta != null) { - var length_1 = this._rotationDelta.lengthSquared(); - var requestedLength = this._requestedRotationDelta.lengthSquared(); - if (requestedLength > length_1) { - this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha); + /** + * Retrieve image tiles. + * + * @description Retrieve a image tiles and render them to the + * texture. Retrieve from store if it exists, otherwise Retrieve + * from loader. + * + * @param {Array>} tiles - Array of tile coordinates to + * retrieve. + */ + TextureProvider.prototype._fetchTiles = function (tiles) { + var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel); + for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) { + var tile = tiles_1[_i]; + var tileKey = this._tileKey(this._tileSize, tile); + if (tileKey in this._renderedCurrentLevelTiles || + tileKey in this._tileSubscriptions) { + continue; } - else { - this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha); + var tileX = tileSize * tile[0]; + var tileY = tileSize * tile[1]; + var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize; + var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize; + if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) { + this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel)); + this._setTileRendered(tile, this._currentLevel); + this._updated$.next(true); + continue; } - this._requestedRotationDelta = null; - return; - } - if (this._rotationDelta.isZero) { - return; + var scaledX = Math.floor(tileWidth / tileSize * this._tileSize); + var scaledY = Math.floor(tileHeight / tileSize * this._tileSize); + this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY); } - this._rotationDelta.multiply(this._rotationAcceleration); - this._rotationDelta.threshold(this._rotationThreshold); }; - TraversingState.prototype._updateRotationBasic = function () { - if (this._requestedBasicRotation != null) { - var x = this._basicRotation[0]; - var y = this._basicRotation[1]; - var lengthSquared = x * x + y * y; - var reqX = this._requestedBasicRotation[0]; - var reqY = this._requestedBasicRotation[1]; - var reqLengthSquared = reqX * reqX + reqY * reqY; - if (reqLengthSquared > lengthSquared) { - this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX; - this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY; + /** + * Get tile coordinates for a point using the current level. + * + * @param {Array} point - Point in basic coordinates. + * + * @returns {Array} x and y tile coodinates. + */ + TextureProvider.prototype._getTileCoords = function (point) { + var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel); + var maxX = Math.ceil(this._width / tileSize) - 1; + var maxY = Math.ceil(this._height / tileSize) - 1; + return [ + Math.min(Math.floor(this._width * point[0] / tileSize), maxX), + Math.min(Math.floor(this._height * point[1] / tileSize), maxY), + ]; + }; + /** + * Get tile coordinates for all tiles contained in a bounding + * box. + * + * @param {Array} topLeft - Top left tile coordinate of bounding box. + * @param {Array} bottomRight - Bottom right tile coordinate of bounding box. + * + * @returns {Array>} Array of x, y tile coodinates. + */ + TextureProvider.prototype._getTiles = function (topLeft, bottomRight) { + var xs = []; + if (topLeft[0] > bottomRight[0]) { + var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel); + var maxX = Math.ceil(this._width / tileSize) - 1; + for (var x = topLeft[0]; x <= maxX; x++) { + xs.push(x); } - else { - this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX; - this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY; + for (var x = 0; x <= bottomRight[0]; x++) { + xs.push(x); } - this._requestedBasicRotation = null; - return; } - if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) { - return; + else { + for (var x = topLeft[0]; x <= bottomRight[0]; x++) { + xs.push(x); + } } - this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0]; - this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1]; - if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) && - Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) { - this._basicRotation = [0, 0]; + var tiles = []; + for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) { + var x = xs_1[_i]; + for (var y = topLeft[1]; y <= bottomRight[1]; y++) { + tiles.push([x, y]); + } } + return tiles; }; - TraversingState.prototype._clearRotation = function () { - if (this._currentNode.fullPano) { - return; - } - if (this._requestedRotationDelta != null) { - this._requestedRotationDelta = null; - } - if (!this._rotationDelta.isZero) { - this._rotationDelta.reset(); - } - if (this._requestedBasicRotation != null) { - this._requestedBasicRotation = null; - } - if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) { - this._basicRotation = [0, 0]; + /** + * Remove an item from an array if it exists in array. + * + * @param {T} item - Item to remove. + * @param {Array} array - Array from which item should be removed. + */ + TextureProvider.prototype._removeFromArray = function (item, array) { + var index = array.indexOf(item); + if (index !== -1) { + array.splice(index, 1); } }; - TraversingState.prototype._setDesiredCenter = function () { - if (this._desiredCenter == null) { - return; + /** + * Remove an item from a dictionary. + * + * @param {string} key - Key of the item to remove. + * @param {Object} dict - Dictionary from which item should be removed. + */ + TextureProvider.prototype._removeFromDictionary = function (key, dict) { + if (key in dict) { + delete dict[key]; } - var lookatDirection = new THREE.Vector3() - .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth)) - .sub(this._currentCamera.position); - this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection)); - this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection)); - this._desiredCenter = null; - }; - TraversingState.prototype._setDesiredZoom = function () { - this._desiredZoom = - this._currentNode.fullPano || this._previousNode == null ? - this._zoom : 0; - }; - return TraversingState; -}(State_1.StateBase)); -exports.TraversingState = TraversingState; - -},{"../../State":214,"three":157,"unitbezier":159}],306:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var State_1 = require("../../State"); -var WaitingState = (function (_super) { - __extends(WaitingState, _super); - function WaitingState(state) { - _super.call(this, state); - this._motionless = this._motionlessTransition(); - } - WaitingState.prototype.traverse = function () { - return new State_1.TraversingState(this); - }; - WaitingState.prototype.wait = function () { - throw new Error("Not implemented"); - }; - WaitingState.prototype.prepend = function (nodes) { - _super.prototype.prepend.call(this, nodes); - this._motionless = this._motionlessTransition(); - }; - WaitingState.prototype.set = function (nodes) { - _super.prototype.set.call(this, nodes); - this._motionless = this._motionlessTransition(); - }; - WaitingState.prototype.rotate = function (delta) { return; }; - WaitingState.prototype.rotateBasic = function (basicRotation) { return; }; - WaitingState.prototype.rotateToBasic = function (basic) { return; }; - WaitingState.prototype.zoomIn = function (delta, reference) { return; }; - WaitingState.prototype.move = function (delta) { - this._alpha = Math.max(0, Math.min(1, this._alpha + delta)); - }; - WaitingState.prototype.moveTo = function (position) { - this._alpha = Math.max(0, Math.min(1, position)); }; - WaitingState.prototype.update = function (fps) { - this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha); - }; - WaitingState.prototype.setCenter = function (center) { return; }; - WaitingState.prototype.setZoom = function (zoom) { return; }; - WaitingState.prototype._getAlpha = function () { - return this._motionless ? Math.ceil(this._alpha) : this._alpha; + /** + * Render an image tile to the target texture. + * + * @param {number} x - The top left x pixel coordinate of the tile. + * @param {number} y - The top left y pixel coordinate of the tile. + * @param {number} w - The pixel width of the tile. + * @param {number} h - The pixel height of the tile. + * @param {HTMLImageElement} background - The image tile to render. + */ + TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) { + var texture = new THREE.Texture(image); + texture.minFilter = THREE.LinearFilter; + texture.needsUpdate = true; + var geometry = new THREE.PlaneGeometry(w, h); + var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide }); + var mesh = new THREE.Mesh(geometry, material); + mesh.position.x = -this._width / 2 + x + w / 2; + mesh.position.y = this._height / 2 - y - h / 2; + var scene = new THREE.Scene(); + scene.add(mesh); + this._renderer.render(scene, this._camera, this._renderTarget); + this._renderer.setRenderTarget(undefined); + scene.remove(mesh); + geometry.dispose(); + material.dispose(); + texture.dispose(); }; - ; - WaitingState.prototype._setCurrentCamera = function () { - _super.prototype._setCurrentCamera.call(this); - if (this._previousNode != null) { - var lookat = this._camera.lookat.clone().sub(this._camera.position); - if (this._previousNode.pano) { - var lookat_1 = this._camera.lookat.clone().sub(this._camera.position); - this._currentCamera.lookat.copy(lookat_1.clone().add(this._currentCamera.position)); + /** + * Mark a tile as rendered. + * + * @description Clears tiles marked as rendered in other + * levels of the tile pyramid if they were rendered on + * top of or below the tile. + * + * @param {Arrary} tile - The tile coordinates. + * @param {number} level - Tile level of the tile coordinates. + */ + TextureProvider.prototype._setTileRendered = function (tile, level) { + var otherLevels = Object.keys(this._renderedTiles) + .map(function (key) { + return parseInt(key, 10); + }) + .filter(function (renderedLevel) { + return renderedLevel !== level; + }); + for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) { + var otherLevel = otherLevels_1[_i]; + var scale = Math.pow(2, otherLevel - level); + if (otherLevel < level) { + var x = Math.floor(scale * tile[0]); + var y = Math.floor(scale * tile[1]); + for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) { + var otherTile = _b[_a]; + if (otherTile[0] === x && otherTile[1] === y) { + var index = this._renderedTiles[otherLevel].indexOf(otherTile); + this._renderedTiles[otherLevel].splice(index, 1); + } + } + } + else { + var startX = scale * tile[0]; + var endX = startX + scale - 1; + var startY = scale * tile[1]; + var endY = startY + scale - 1; + for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) { + var otherTile = _d[_c]; + if (otherTile[0] >= startX && otherTile[0] <= endX && + otherTile[1] >= startY && otherTile[1] <= endY) { + var index = this._renderedTiles[otherLevel].indexOf(otherTile); + this._renderedTiles[otherLevel].splice(index, 1); + } + } } - if (this._currentNode.pano) { - this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position)); + if (this._renderedTiles[otherLevel].length === 0) { + delete this._renderedTiles[otherLevel]; } } + this._renderedTiles[level].push(tile); + this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true; + }; + /** + * Create a tile key from a tile coordinates. + * + * @description Tile keys are used as a hash for + * storing the tile in a dictionary. + * + * @param {number} tileSize - The tile size. + * @param {Arrary} tile - The tile coordinates. + */ + TextureProvider.prototype._tileKey = function (tileSize, tile) { + return tileSize + "-" + tile[0] + "-" + tile[1]; + }; + return TextureProvider; +}()); +exports.TextureProvider = TextureProvider; +exports.default = TextureProvider; + +},{"rxjs/Subject":34,"three":240}],430:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var DOM = /** @class */ (function () { + function DOM(doc) { + this._document = !!doc ? doc : document; + } + Object.defineProperty(DOM.prototype, "document", { + get: function () { + return this._document; + }, + enumerable: true, + configurable: true + }); + DOM.prototype.createElement = function (tagName, className, container) { + var element = this._document.createElement(tagName); + if (!!className) { + element.className = className; + } + if (!!container) { + container.appendChild(element); + } + return element; }; - return WaitingState; -}(State_1.StateBase)); -exports.WaitingState = WaitingState; + return DOM; +}()); +exports.DOM = DOM; +exports.default = DOM; -},{"../../State":214}],307:[function(require,module,exports){ +},{}],431:[function(require,module,exports){ "use strict"; -var EventEmitter = (function () { +Object.defineProperty(exports, "__esModule", { value: true }); +var EventEmitter = /** @class */ (function () { function EventEmitter() { this._events = {}; } @@ -31871,13 +44991,13 @@ var EventEmitter = (function () { return EventEmitter; }()); exports.EventEmitter = EventEmitter; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = EventEmitter; -},{}],308:[function(require,module,exports){ +},{}],432:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Viewer_1 = require("../Viewer"); -var Settings = (function () { +var Settings = /** @class */ (function () { function Settings() { } Settings.setOptions = function (options) { @@ -31915,43 +45035,325 @@ var Settings = (function () { return Settings; }()); exports.Settings = Settings; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Settings; -},{"../Viewer":216}],309:[function(require,module,exports){ +},{"../Viewer":301}],433:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function isBrowser() { + return typeof window !== "undefined" && typeof document !== "undefined"; +} +exports.isBrowser = isBrowser; +function isArraySupported() { + return !!(Array.prototype && + Array.prototype.filter && + Array.prototype.indexOf && + Array.prototype.map && + Array.prototype.reverse); +} +exports.isArraySupported = isArraySupported; +function isFunctionSupported() { + return !!(Function.prototype && Function.prototype.bind); +} +exports.isFunctionSupported = isFunctionSupported; +function isJSONSupported() { + return "JSON" in window && "parse" in JSON && "stringify" in JSON; +} +exports.isJSONSupported = isJSONSupported; +function isObjectSupported() { + return !!(Object.keys && + Object.assign); +} +exports.isObjectSupported = isObjectSupported; +function isBlobSupported() { + return "Blob" in window && "URL" in window; +} +exports.isBlobSupported = isBlobSupported; +var isWebGLSupportedCache = undefined; +function isWebGLSupportedCached() { + if (isWebGLSupportedCache === undefined) { + isWebGLSupportedCache = isWebGLSupported(); + } + return isWebGLSupportedCache; +} +exports.isWebGLSupportedCached = isWebGLSupportedCached; +function isWebGLSupported() { + var webGLContextAttributes = { + alpha: false, + antialias: false, + depth: true, + failIfMajorPerformanceCaveat: false, + premultipliedAlpha: true, + preserveDrawingBuffer: false, + stencil: true, + }; + var canvas = document.createElement("canvas"); + var context = canvas.getContext("webgl", webGLContextAttributes) || + canvas.getContext("experimental-webgl", webGLContextAttributes); + if (!context) { + return false; + } + var requiredExtensions = [ + "OES_standard_derivatives", + ]; + var supportedExtensions = context.getSupportedExtensions(); + for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) { + var requiredExtension = requiredExtensions_1[_i]; + if (supportedExtensions.indexOf(requiredExtension) === -1) { + return false; + } + } + return true; +} +exports.isWebGLSupported = isWebGLSupported; + +},{}],434:[function(require,module,exports){ "use strict"; -var Urls = (function () { +Object.defineProperty(exports, "__esModule", { value: true }); +var Urls = /** @class */ (function () { function Urls() { } - Urls.dynamicImage = function (key, size) { - return "https://d2qb1440i7l50o.cloudfront.net/" + key + "/full/!" + size + "," + size + "/0/default.jpg?origin=mapillary.webgl"; + Object.defineProperty(Urls, "explore", { + get: function () { + return Urls._scheme + "://" + Urls._exploreHost; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Urls, "origin", { + get: function () { + return Urls._origin; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Urls, "tileScheme", { + get: function () { + return Urls._scheme; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Urls, "tileDomain", { + get: function () { + return Urls._imageTileHost; + }, + enumerable: true, + configurable: true + }); + Urls.exporeImage = function (key) { + return Urls._scheme + "://" + Urls._exploreHost + "/app/?pKey=" + key + "&focus=photo"; }; - Urls.thumbnail = function (key, size) { - return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=mapillary.webgl"; + Urls.exporeUser = function (username) { + return Urls._scheme + "://" + Urls._exploreHost + "/app/user/" + username; }; Urls.falcorModel = function (clientId) { - return "https://a.mapillary.com/v3/model.json?client_id=" + clientId; + return Urls._scheme + "://" + Urls._apiHost + "/v3/model.json?client_id=" + clientId; }; Urls.protoMesh = function (key) { - return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key; + return Urls._scheme + "://" + Urls._meshHost + "/v2/mesh/" + key; + }; + Urls.thumbnail = function (key, size, origin) { + var query = !!origin ? "?origin=" + origin : ""; + return Urls._scheme + "://" + Urls._imageHost + "/" + key + "/thumb-" + size + ".jpg" + query; + }; + Urls.setOptions = function (options) { + if (!options) { + return; + } + if (!!options.apiHost) { + Urls._apiHost = options.apiHost; + } + if (!!options.exploreHost) { + Urls._exploreHost = options.exploreHost; + } + if (!!options.imageHost) { + Urls._imageHost = options.imageHost; + } + if (!!options.imageTileHost) { + Urls._imageTileHost = options.imageTileHost; + } + if (!!options.meshHost) { + Urls._meshHost = options.meshHost; + } + if (!!options.scheme) { + Urls._scheme = options.scheme; + } }; + Urls._apiHost = "a.mapillary.com"; + Urls._exploreHost = "www.mapillary.com"; + Urls._imageHost = "d1cuyjsrcm0gby.cloudfront.net"; + Urls._imageTileHost = "d2qb1440i7l50o.cloudfront.net"; + Urls._meshHost = "d1brzeo354iq2l.cloudfront.net"; + Urls._origin = "mapillary.webgl"; + Urls._scheme = "https"; return Urls; }()); exports.Urls = Urls; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Urls; -},{}],310:[function(require,module,exports){ +},{}],435:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Enumeration for alignments + * @enum {number} + * @readonly + */ +var Alignment; +(function (Alignment) { + /** + * Align to bottom + */ + Alignment[Alignment["Bottom"] = 0] = "Bottom"; + /** + * Align to bottom left + */ + Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft"; + /** + * Align to bottom right + */ + Alignment[Alignment["BottomRight"] = 2] = "BottomRight"; + /** + * Align to center + */ + Alignment[Alignment["Center"] = 3] = "Center"; + /** + * Align to left + */ + Alignment[Alignment["Left"] = 4] = "Left"; + /** + * Align to right + */ + Alignment[Alignment["Right"] = 5] = "Right"; + /** + * Align to top + */ + Alignment[Alignment["Top"] = 6] = "Top"; + /** + * Align to top left + */ + Alignment[Alignment["TopLeft"] = 7] = "TopLeft"; + /** + * Align to top right + */ + Alignment[Alignment["TopRight"] = 8] = "TopRight"; +})(Alignment = exports.Alignment || (exports.Alignment = {})); +exports.default = Alignment; + +},{}],436:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Graph_1 = require("../Graph"); +var CacheService = /** @class */ (function () { + function CacheService(graphService, stateService) { + this._graphService = graphService; + this._stateService = stateService; + this._started = false; + } + Object.defineProperty(CacheService.prototype, "started", { + get: function () { + return this._started; + }, + enumerable: true, + configurable: true + }); + CacheService.prototype.start = function () { + var _this = this; + if (this._started) { + return; + } + this._uncacheSubscription = this._stateService.currentState$ + .distinctUntilChanged(undefined, function (frame) { + return frame.state.currentNode.key; + }) + .map(function (frame) { + var trajectory = frame.state.trajectory; + var trajectoryKeys = trajectory + .map(function (n) { + return n.key; + }); + var sequenceKey = trajectory[trajectory.length - 1].sequenceKey; + return [trajectoryKeys, sequenceKey]; + }) + .bufferCount(1, 5) + .withLatestFrom(this._graphService.graphMode$) + .switchMap(function (_a) { + var keepBuffer = _a[0], graphMode = _a[1]; + var keepKeys = keepBuffer[0][0]; + var keepSequenceKey = graphMode === Graph_1.GraphMode.Sequence ? + keepBuffer[0][1] : undefined; + return _this._graphService.uncache$(keepKeys, keepSequenceKey); + }) + .subscribe(function () { }); + this._cacheNodeSubscription = this._graphService.graphMode$ + .skip(1) + .withLatestFrom(this._stateService.currentState$) + .switchMap(function (_a) { + var mode = _a[0], frame = _a[1]; + return mode === Graph_1.GraphMode.Sequence ? + _this._keyToEdges(frame.state.currentNode.key, function (node) { + return node.sequenceEdges$; + }) : + Observable_1.Observable + .from(frame.state.trajectory + .map(function (node) { + return node.key; + }) + .slice(frame.state.currentIndex)) + .mergeMap(function (key) { + return _this._keyToEdges(key, function (node) { + return node.spatialEdges$; + }); + }, 6); + }) + .subscribe(function () { }); + this._started = true; + }; + CacheService.prototype.stop = function () { + if (!this._started) { + return; + } + this._uncacheSubscription.unsubscribe(); + this._uncacheSubscription = null; + this._cacheNodeSubscription.unsubscribe(); + this._cacheNodeSubscription = null; + this._started = false; + }; + CacheService.prototype._keyToEdges = function (key, nodeToEdgeMap) { + return this._graphService.cacheNode$(key) + .switchMap(nodeToEdgeMap) + .first(function (status) { + return status.cached; + }) + .timeout(15000) + .catch(function (error) { + console.error("Failed to cache edges (" + key + ").", error); + return Observable_1.Observable.empty(); + }); + }; + return CacheService; +}()); +exports.CacheService = CacheService; +exports.default = CacheService; + +},{"../Graph":294,"rxjs/Observable":29}],437:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Component_1 = require("../Component"); -var ComponentController = (function () { - function ComponentController(container, navigator, key, options) { +var ComponentController = /** @class */ (function () { + function ComponentController(container, navigator, observer, key, options, componentService) { var _this = this; this._container = container; + this._observer = observer; this._navigator = navigator; this._options = options != null ? options : {}; this._key = key; - this._componentService = new Component_1.ComponentService(this._container, this._navigator); + this._navigable = key == null; + this._componentService = !!componentService ? + componentService : + new Component_1.ComponentService(this._container, this._navigator); this._coverComponent = this._componentService.getCover(); this._initializeComponents(); if (key) { @@ -31960,16 +45362,27 @@ var ComponentController = (function () { } else { this._navigator.movedToKey$ - .first() - .subscribe(function (movedToKey) { - _this._key = movedToKey; + .first(function (k) { + return k != null; + }) + .subscribe(function (k) { + _this._key = k; _this._componentService.deactivateCover(); - _this._coverComponent.configure({ key: _this._key, loading: false, visible: false }); + _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden }); _this._subscribeCoverComponent(); _this._navigator.stateService.start(); + _this._navigator.cacheService.start(); + _this._observer.startEmit(); }); } } + Object.defineProperty(ComponentController.prototype, "navigable", { + get: function () { + return this._navigable; + }, + enumerable: true, + configurable: true + }); ComponentController.prototype.get = function (name) { return this._componentService.get(name); }; @@ -31977,13 +45390,13 @@ var ComponentController = (function () { this._componentService.activate(name); }; ComponentController.prototype.activateCover = function () { - this._coverComponent.configure({ loading: false, visible: true }); + this._coverComponent.configure({ state: Component_1.CoverState.Visible }); }; ComponentController.prototype.deactivate = function (name) { this._componentService.deactivate(name); }; ComponentController.prototype.deactivateCover = function () { - this._coverComponent.configure({ loading: true, visible: true }); + this._coverComponent.configure({ state: Component_1.CoverState.Loading }); }; ComponentController.prototype.resize = function () { this._componentService.resize(); @@ -31995,9 +45408,9 @@ var ComponentController = (function () { this._uFalse(options.image, "image"); this._uFalse(options.marker, "marker"); this._uFalse(options.navigation, "navigation"); + this._uFalse(options.popup, "popup"); this._uFalse(options.route, "route"); this._uFalse(options.slider, "slider"); - this._uFalse(options.stats, "stats"); this._uFalse(options.tag, "tag"); this._uTrue(options.attribution, "attribution"); this._uTrue(options.bearing, "bearing"); @@ -32008,6 +45421,8 @@ var ComponentController = (function () { this._uTrue(options.loading, "loading"); this._uTrue(options.mouse, "mouse"); this._uTrue(options.sequence, "sequence"); + this._uTrue(options.stats, "stats"); + this._uTrue(options.zoom, "zoom"); }; ComponentController.prototype._initilizeCoverComponent = function () { var options = this._options; @@ -32019,23 +45434,48 @@ var ComponentController = (function () { this.deactivateCover(); } }; + ComponentController.prototype._setNavigable = function (navigable) { + if (this._navigable === navigable) { + return; + } + this._navigable = navigable; + this._observer.navigable$.next(navigable); + }; ComponentController.prototype._subscribeCoverComponent = function () { var _this = this; this._coverComponent.configuration$.subscribe(function (conf) { - if (conf.loading) { - _this._navigator.moveToKey$(conf.key) + if (conf.state === Component_1.CoverState.Loading) { + _this._navigator.stateService.currentKey$ + .first() + .switchMap(function (key) { + var keyChanged = key == null || key !== conf.key; + if (keyChanged) { + _this._setNavigable(false); + } + return keyChanged ? + _this._navigator.moveToKey$(conf.key) : + _this._navigator.stateService.currentNode$ + .first(); + }) .subscribe(function (node) { _this._navigator.stateService.start(); - _this._coverComponent.configure({ loading: false, visible: false }); + _this._navigator.cacheService.start(); + _this._observer.startEmit(); + _this._coverComponent.configure({ state: Component_1.CoverState.Hidden }); _this._componentService.deactivateCover(); + _this._setNavigable(true); }, function (error) { console.error("Failed to deactivate cover.", error); - _this._coverComponent.configure({ loading: false, visible: true }); + _this._coverComponent.configure({ state: Component_1.CoverState.Visible }); }); } - else if (conf.visible) { + else if (conf.state === Component_1.CoverState.Visible) { + _this._observer.stopEmit(); _this._navigator.stateService.stop(); + _this._navigator.cacheService.stop(); + _this._navigator.playService.stop(); _this._componentService.activateCover(); + _this._setNavigable(conf.key == null); } }); }; @@ -32077,96 +45517,67 @@ var ComponentController = (function () { }()); exports.ComponentController = ComponentController; -},{"../Component":207}],311:[function(require,module,exports){ +},{"../Component":290}],438:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var Render_1 = require("../Render"); +var Utils_1 = require("../Utils"); var Viewer_1 = require("../Viewer"); -var Container = (function () { - function Container(id, stateService, options) { +var Container = /** @class */ (function () { + function Container(id, stateService, options, dom) { this.id = id; - this.element = document.getElementById(id); - this.element.classList.add("mapillary-js"); - this.renderService = new Render_1.RenderService(this.element, stateService.currentState$, options.renderMode); - this.glRenderer = new Render_1.GLRenderer(this.renderService); - this.domRenderer = new Render_1.DOMRenderer(this.element, this.renderService, stateService.currentState$); - this.mouseService = new Viewer_1.MouseService(this.element); - this.touchService = new Viewer_1.TouchService(this.element); + this._dom = !!dom ? dom : new Utils_1.DOM(); + this._container = this._dom.document.getElementById(id); + if (!this._container) { + throw new Error("Container '" + id + "' not found."); + } + this._container.classList.add("mapillary-js"); + this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container); + this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container); + this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode); + this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom); + this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$); + this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer); + this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document); + this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer); this.spriteService = new Viewer_1.SpriteService(options.sprite); } + Object.defineProperty(Container.prototype, "element", { + get: function () { + return this._container; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Container.prototype, "canvasContainer", { + get: function () { + return this._canvasContainer; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Container.prototype, "domContainer", { + get: function () { + return this._domContainer; + }, + enumerable: true, + configurable: true + }); return Container; }()); exports.Container = Container; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Container; -},{"../Render":213,"../Viewer":216}],312:[function(require,module,exports){ +},{"../Render":296,"../Utils":300,"../Viewer":301}],439:[function(require,module,exports){ "use strict"; -var Observable_1 = require("rxjs/Observable"); -require("rxjs/add/observable/combineLatest"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/map"); -var Viewer_1 = require("../Viewer"); -var EventLauncher = (function () { - function EventLauncher(eventEmitter, navigator, container) { - var _this = this; - this._container = container; - this._eventEmitter = eventEmitter; - this._navigator = navigator; - this._loadingSubscription = this._navigator.loadingService.loading$ - .subscribe(function (loading) { - _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading); - }); - this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$ - .subscribe(function (node) { - _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node); - }); - this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$ - .switchMap(function (node) { - return node.sequenceEdges$; - }) - .subscribe(function (status) { - _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status); - }); - this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$ - .switchMap(function (node) { - return node.spatialEdges$; - }) - .subscribe(function (status) { - _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status); - }); - Observable_1.Observable - .combineLatest(this._navigator.stateService.moving$, this._container.mouseService.active$) - .map(function (values) { - return values[0] || values[1]; - }) - .distinctUntilChanged() - .subscribe(function (started) { - if (started) { - _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null); - } - else { - _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null); - } - }); - } - EventLauncher.prototype.dispose = function () { - this._loadingSubscription.unsubscribe(); - this._currentNodeSubscription.unsubscribe(); - }; - return EventLauncher; -}()); -exports.EventLauncher = EventLauncher; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = EventLauncher; - -},{"../Viewer":216,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/map":60}],313:[function(require,module,exports){ -"use strict"; /** * Enumeration for image sizes * @enum {number} * @readonly * @description Image sizes in pixels for the long side of the image. */ +var ImageSize; (function (ImageSize) { /** * 320 pixels image size @@ -32184,21 +45595,35 @@ exports.default = EventLauncher; * 2048 pixels image size */ ImageSize[ImageSize["Size2048"] = 2048] = "Size2048"; -})(exports.ImageSize || (exports.ImageSize = {})); -var ImageSize = exports.ImageSize; +})(ImageSize = exports.ImageSize || (exports.ImageSize = {})); -},{}],314:[function(require,module,exports){ -/// +},{}],440:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var KeyboardService = /** @class */ (function () { + function KeyboardService(canvasContainer) { + this._keyDown$ = Observable_1.Observable.fromEvent(canvasContainer, "keydown"); + } + Object.defineProperty(KeyboardService.prototype, "keyDown$", { + get: function () { + return this._keyDown$; + }, + enumerable: true, + configurable: true + }); + return KeyboardService; +}()); +exports.KeyboardService = KeyboardService; +exports.default = KeyboardService; + +},{"rxjs/Observable":29}],441:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var _ = require("underscore"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/debounceTime"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/startWith"); -var LoadingService = (function () { +var LoadingService = /** @class */ (function () { function LoadingService() { this._loadersSubject$ = new Subject_1.Subject(); this._loaders$ = this._loadersSubject$ @@ -32243,140 +45668,147 @@ var LoadingService = (function () { return LoadingService; }()); exports.LoadingService = LoadingService; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = LoadingService; -},{"rxjs/Subject":33,"rxjs/add/operator/debounceTime":51,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/map":60,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/startWith":72,"underscore":158}],315:[function(require,module,exports){ -/// +},{"rxjs/Subject":34,"underscore":242}],442:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/fromEvent"); -require("rxjs/add/operator/distinctUntilChanged"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/merge"); -require("rxjs/add/operator/mergeMap"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/switchMap"); -require("rxjs/add/operator/withLatestFrom"); -var MouseService = (function () { - function MouseService(element) { +var Geo_1 = require("../Geo"); +var MouseService = /** @class */ (function () { + function MouseService(container, canvasContainer, domContainer, doc, viewportCoords) { var _this = this; - this._element = element; + viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords(); this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false); this._active$ = this._activeSubject$ .distinctUntilChanged() .publishReplay(1) .refCount(); - this._preventMouseDownOperation$ = new Subject_1.Subject(); - this._preventMouseDown$ = new Subject_1.Subject(); - this._mouseMoveOperation$ = new Subject_1.Subject(); this._claimMouse$ = new Subject_1.Subject(); - this._mouseDown$ = Observable_1.Observable.fromEvent(element, "mousedown"); - this._mouseLeave$ = Observable_1.Observable.fromEvent(element, "mouseleave"); - this._mouseUp$ = Observable_1.Observable.fromEvent(element, "mouseup"); - this._mouseOver$ = Observable_1.Observable.fromEvent(element, "mouseover"); - this._click$ = Observable_1.Observable.fromEvent(element, "click"); - this._mouseWheel$ = Observable_1.Observable.fromEvent(element, "wheel"); - this._mouseWheel$ + this._claimWheel$ = new Subject_1.Subject(); + this._deferPixelClaims$ = new Subject_1.Subject(); + this._deferPixels$ = this._deferPixelClaims$ + .scan(function (claims, claim) { + if (claim.deferPixels == null) { + delete claims[claim.name]; + } + else { + claims[claim.name] = claim.deferPixels; + } + return claims; + }, {}) + .map(function (claims) { + var deferPixelMax = -1; + for (var key in claims) { + if (!claims.hasOwnProperty(key)) { + continue; + } + var deferPixels = claims[key]; + if (deferPixels > deferPixelMax) { + deferPixelMax = deferPixels; + } + } + return deferPixelMax; + }) + .startWith(-1) + .publishReplay(1) + .refCount(); + this._deferPixels$.subscribe(function () { }); + this._documentMouseMove$ = Observable_1.Observable.fromEvent(doc, "mousemove"); + this._documentMouseUp$ = Observable_1.Observable.fromEvent(doc, "mouseup"); + this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown"); + this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave"); + this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove"); + this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup"); + this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout"); + this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover"); + this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown"); + this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove"); + this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click"); + this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu"); + this._dblClick$ = Observable_1.Observable + .merge(Observable_1.Observable.fromEvent(container, "click"), Observable_1.Observable.fromEvent(canvasContainer, "dblclick")) + .bufferCount(3, 1) + .filter(function (events) { + var event1 = events[0]; + var event2 = events[1]; + var event3 = events[2]; + return event1.type === "click" && + event2.type === "click" && + event3.type === "dblclick" && + event1.target.parentNode === canvasContainer && + event2.target.parentNode === canvasContainer; + }) + .map(function (events) { + return events[2]; + }) + .share(); + Observable_1.Observable + .merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$) .subscribe(function (event) { event.preventDefault(); }); - this._preventMouseDownOperation$ - .scan(function (prevent, operation) { - return operation(prevent); - }, true) - .subscribe(); - this._preventMouseDown$ - .map(function (prevent) { - return function (previous) { - return prevent; - }; - }) - .subscribe(this._preventMouseDownOperation$); - this._mouseDown$ - .map(function (e) { - return function (prevent) { - if (prevent) { - e.preventDefault(); - } - return prevent; - }; + this._mouseWheel$ = Observable_1.Observable + .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel")) + .share(); + this._consistentContextMenu$ = Observable_1.Observable + .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$) + .bufferCount(3, 1) + .filter(function (events) { + // fire context menu on mouse up both on mac and windows + return events[0].type === "mousedown" && + events[1].type === "contextmenu" && + events[2].type === "mouseup"; }) - .subscribe(this._preventMouseDownOperation$); - this._mouseMove$ = this._mouseMoveOperation$ - .scan(function (e, operation) { - return operation(e); - }, null); - Observable_1.Observable - .fromEvent(element, "mousemove") - .map(function (e) { - return function (previous) { - if (previous == null) { - previous = e; - } - if (e.movementX == null) { - e.movementX = e.clientX - previous.clientX; - } - if (e.movementY == null) { - e.movementY = e.clientY - previous.clientY; - } - return e; - }; + .map(function (events) { + return events[1]; }) - .subscribe(this._mouseMoveOperation$); + .share(); var dragStop$ = Observable_1.Observable - .merge(this._mouseLeave$, this._mouseUp$); - this._mouseDragStart$ = this._mouseDown$ - .mergeMap(function (e) { - return _this._mouseMove$ - .takeUntil(dragStop$) + .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$ + .filter(function (e) { + return e.button === 0; + })) + .share(); + var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).share(); + this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).share(); + this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).share(); + this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).share(); + var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).share(); + this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).share(); + this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).share(); + this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).share(); + this._proximateClick$ = this._mouseDown$ + .switchMap(function (mouseDown) { + return _this._click$ + .takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$)) .take(1); - }); - this._mouseDrag$ = this._mouseDown$ - .mergeMap(function (e) { - return _this._mouseMove$ - .skip(1) - .takeUntil(dragStop$); - }); - this._mouseDragEnd$ = this._mouseDragStart$ - .mergeMap(function (e) { - return dragStop$.first(); - }); + }) + .share(); this._staticClick$ = this._mouseDown$ .switchMap(function (e) { return _this._click$ - .takeUntil(_this._mouseMove$) + .takeUntil(_this._documentMouseMove$) .take(1); - }); - this._mouseOwner$ = this._claimMouse$ - .scan(function (claims, mouseClaim) { - if (mouseClaim.zindex == null) { - delete claims[mouseClaim.name]; - } - else { - claims[mouseClaim.name] = mouseClaim.zindex; - } - return claims; - }, {}) - .map(function (claims) { - var owner = null; - var curZ = -1; - for (var name_1 in claims) { - if (claims.hasOwnProperty(name_1)) { - if (claims[name_1] > curZ) { - curZ = claims[name_1]; - owner = name_1; - } - } - } - return owner; }) + .share(); + this._mouseDragStart$.subscribe(); + this._mouseDrag$.subscribe(); + this._mouseDragEnd$.subscribe(); + this._domMouseDragStart$.subscribe(); + this._domMouseDrag$.subscribe(); + this._domMouseDragEnd$.subscribe(); + this._staticClick$.subscribe(); + this._mouseOwner$ = this._createOwner$(this._claimMouse$) .publishReplay(1) .refCount(); + this._wheelOwner$ = this._createOwner$(this._claimWheel$) + .publishReplay(1) + .refCount(); + this._mouseOwner$.subscribe(function () { }); + this._wheelOwner$.subscribe(function () { }); } Object.defineProperty(MouseService.prototype, "active$", { get: function () { @@ -32392,6 +45824,55 @@ var MouseService = (function () { enumerable: true, configurable: true }); + Object.defineProperty(MouseService.prototype, "documentMouseMove$", { + get: function () { + return this._documentMouseMove$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "documentMouseUp$", { + get: function () { + return this._documentMouseUp$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "domMouseDragStart$", { + get: function () { + return this._domMouseDragStart$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "domMouseDrag$", { + get: function () { + return this._domMouseDrag$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", { + get: function () { + return this._domMouseDragEnd$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "domMouseDown$", { + get: function () { + return this._domMouseDown$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "domMouseMove$", { + get: function () { + return this._domMouseMove$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(MouseService.prototype, "mouseOwner$", { get: function () { return this._mouseOwner$; @@ -32420,6 +45901,20 @@ var MouseService = (function () { enumerable: true, configurable: true }); + Object.defineProperty(MouseService.prototype, "mouseOut$", { + get: function () { + return this._mouseOut$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "mouseOver$", { + get: function () { + return this._mouseOver$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(MouseService.prototype, "mouseUp$", { get: function () { return this._mouseUp$; @@ -32434,6 +45929,20 @@ var MouseService = (function () { enumerable: true, configurable: true }); + Object.defineProperty(MouseService.prototype, "dblClick$", { + get: function () { + return this._dblClick$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MouseService.prototype, "contextMenu$", { + get: function () { + return this._consistentContextMenu$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(MouseService.prototype, "mouseWheel$", { get: function () { return this._mouseWheel$; @@ -32462,16 +45971,16 @@ var MouseService = (function () { enumerable: true, configurable: true }); - Object.defineProperty(MouseService.prototype, "staticClick$", { + Object.defineProperty(MouseService.prototype, "proximateClick$", { get: function () { - return this._staticClick$; + return this._proximateClick$; }, enumerable: true, configurable: true }); - Object.defineProperty(MouseService.prototype, "preventDefaultMouseDown$", { + Object.defineProperty(MouseService.prototype, "staticClick$", { get: function () { - return this._preventMouseDown$; + return this._staticClick$; }, enumerable: true, configurable: true @@ -32479,193 +45988,1016 @@ var MouseService = (function () { MouseService.prototype.claimMouse = function (name, zindex) { this._claimMouse$.next({ name: name, zindex: zindex }); }; - MouseService.prototype.unclaimMouse = function (name) { - this._claimMouse$.next({ name: name, zindex: null }); + MouseService.prototype.unclaimMouse = function (name) { + this._claimMouse$.next({ name: name, zindex: null }); + }; + MouseService.prototype.deferPixels = function (name, deferPixels) { + this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels }); + }; + MouseService.prototype.undeferPixels = function (name) { + this._deferPixelClaims$.next({ name: name, deferPixels: null }); + }; + MouseService.prototype.claimWheel = function (name, zindex) { + this._claimWheel$.next({ name: name, zindex: zindex }); + }; + MouseService.prototype.unclaimWheel = function (name) { + this._claimWheel$.next({ name: name, zindex: null }); + }; + MouseService.prototype.filtered$ = function (name, observable$) { + return this._filtered(name, observable$, this._mouseOwner$); + }; + MouseService.prototype.filteredWheel$ = function (name, observable$) { + return this._filtered(name, observable$, this._wheelOwner$); + }; + MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) { + return mouseMove$ + .map(function (mouseMove) { + var deltaX = mouseMove.clientX - origin.clientX; + var deltaY = mouseMove.clientY - origin.clientY; + return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)]; + }) + .withLatestFrom(this._deferPixels$) + .filter(function (_a) { + var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1]; + return delta > deferPixels; + }) + .map(function (_a) { + var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1]; + return mouseMove; + }); + }; + MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) { + var _this = this; + return mouseDragStartInitiate$ + .map(function (_a) { + var mouseDown = _a[0], mouseMove = _a[1]; + return mouseMove; + }) + .switchMap(function (mouseMove) { + return Observable_1.Observable + .of(mouseMove) + .concat(_this._documentMouseMove$) + .takeUntil(stop$); + }); + }; + MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) { + return mouseDragStart$ + .switchMap(function (event) { + return stop$.first(); + }); + }; + MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) { + return mouseDragStartInitiate$ + .map(function (_a) { + var mouseDown = _a[0], mouseMove = _a[1]; + return mouseDown; + }); + }; + MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) { + var _this = this; + return mouseDown$ + .filter(function (mouseDown) { + return mouseDown.button === 0; + }) + .switchMap(function (mouseDown) { + return Observable_1.Observable + .combineLatest(Observable_1.Observable.of(mouseDown), defer ? + _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) : + _this._documentMouseMove$) + .takeUntil(stop$) + .take(1); + }); + }; + MouseService.prototype._createOwner$ = function (claim$) { + return claim$ + .scan(function (claims, claim) { + if (claim.zindex == null) { + delete claims[claim.name]; + } + else { + claims[claim.name] = claim.zindex; + } + return claims; + }, {}) + .map(function (claims) { + var owner = null; + var zIndexMax = -1; + for (var name_1 in claims) { + if (!claims.hasOwnProperty(name_1)) { + continue; + } + if (claims[name_1] > zIndexMax) { + zIndexMax = claims[name_1]; + owner = name_1; + } + } + return owner; + }) + .startWith(null); + }; + MouseService.prototype._filtered = function (name, observable$, owner$) { + return observable$ + .withLatestFrom(owner$) + .filter(function (_a) { + var item = _a[0], owner = _a[1]; + return owner === name; + }) + .map(function (_a) { + var item = _a[0], owner = _a[1]; + return item; + }); + }; + return MouseService; +}()); +exports.MouseService = MouseService; +exports.default = MouseService; + +},{"../Geo":293,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34}],443:[function(require,module,exports){ +"use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); +var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); +var Observable_1 = require("rxjs/Observable"); +var ReplaySubject_1 = require("rxjs/ReplaySubject"); +var API_1 = require("../API"); +var Graph_1 = require("../Graph"); +var Edge_1 = require("../Edge"); +var Error_1 = require("../Error"); +var State_1 = require("../State"); +var Viewer_1 = require("../Viewer"); +var Navigator = /** @class */ (function () { + function Navigator(clientId, options, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService, playService) { + this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token); + this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService(); + this._graphService = graphService != null ? + graphService : + new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService); + this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService(); + this._loadingName = "navigator"; + this._stateService = stateService != null ? stateService : new State_1.StateService(options.transitionMode); + this._cacheService = cacheService != null ? + cacheService : + new Viewer_1.CacheService(this._graphService, this._stateService); + this._playService = playService != null ? + playService : + new Viewer_1.PlayService(this._graphService, this._stateService); + this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null); + this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null); + this._request$ = null; + this._requestSubscription = null; + this._nodeRequestSubscription = null; + } + Object.defineProperty(Navigator.prototype, "apiV3", { + get: function () { + return this._apiV3; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Navigator.prototype, "cacheService", { + get: function () { + return this._cacheService; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Navigator.prototype, "graphService", { + get: function () { + return this._graphService; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Navigator.prototype, "imageLoadingService", { + get: function () { + return this._imageLoadingService; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Navigator.prototype, "loadingService", { + get: function () { + return this._loadingService; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Navigator.prototype, "movedToKey$", { + get: function () { + return this._movedToKey$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Navigator.prototype, "playService", { + get: function () { + return this._playService; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Navigator.prototype, "stateService", { + get: function () { + return this._stateService; + }, + enumerable: true, + configurable: true + }); + Navigator.prototype.moveToKey$ = function (key) { + this._abortRequest("to key " + key); + this._loadingService.startLoading(this._loadingName); + var node$ = this._moveToKey$(key); + return this._makeRequest$(node$); + }; + Navigator.prototype.moveDir$ = function (direction) { + var _this = this; + this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]); + this._loadingService.startLoading(this._loadingName); + var node$ = this.stateService.currentNode$ + .first() + .mergeMap(function (node) { + return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ? + node.sequenceEdges$ : + node.spatialEdges$) + .first() + .map(function (status) { + for (var _i = 0, _a = status.edges; _i < _a.length; _i++) { + var edge = _a[_i]; + if (edge.data.direction === direction) { + return edge.to; + } + } + return null; + }); + }) + .mergeMap(function (directionKey) { + if (directionKey == null) { + _this._loadingService.stopLoading(_this._loadingName); + return Observable_1.Observable + .throw(new Error("Direction (" + direction + ") does not exist for current node.")); + } + return _this._moveToKey$(directionKey); + }); + return this._makeRequest$(node$); + }; + Navigator.prototype.moveCloseTo$ = function (lat, lon) { + var _this = this; + this._abortRequest("to lat " + lat + ", lon " + lon); + this._loadingService.startLoading(this._loadingName); + var node$ = this.apiV3.imageCloseTo$(lat, lon) + .mergeMap(function (fullNode) { + if (fullNode == null) { + _this._loadingService.stopLoading(_this._loadingName); + return Observable_1.Observable + .throw(new Error("No image found close to lat " + lat + ", lon " + lon + ".")); + } + return _this._moveToKey$(fullNode.key); + }); + return this._makeRequest$(node$); }; - MouseService.prototype.filtered$ = function (name, observable$) { - return observable$ - .withLatestFrom(this.mouseOwner$, function (event, owner) { - return [event, owner]; + Navigator.prototype.setFilter$ = function (filter) { + var _this = this; + this._stateService.clearNodes(); + return this._movedToKey$ + .first() + .mergeMap(function (key) { + if (key != null) { + return _this._trajectoryKeys$() + .mergeMap(function (keys) { + return _this._graphService.setFilter$(filter) + .mergeMap(function () { + return _this._cacheKeys$(keys); + }); + }) + .last(); + } + return _this._keyRequested$ + .first() + .mergeMap(function (requestedKey) { + if (requestedKey != null) { + return _this._graphService.setFilter$(filter) + .mergeMap(function () { + return _this._graphService.cacheNode$(requestedKey); + }); + } + return _this._graphService.setFilter$(filter) + .map(function () { + return undefined; + }); + }); }) - .filter(function (eo) { - return eo[1] === name; + .map(function (node) { + return undefined; + }); + }; + Navigator.prototype.setToken$ = function (token) { + var _this = this; + this._abortRequest("to set token"); + this._stateService.clearNodes(); + return this._movedToKey$ + .first() + .do(function (key) { + _this._apiV3.setToken(token); }) - .map(function (eo) { - return eo[0]; + .mergeMap(function (key) { + return key == null ? + _this._graphService.reset$([]) : + _this._trajectoryKeys$() + .mergeMap(function (keys) { + return _this._graphService.reset$(keys) + .mergeMap(function () { + return _this._cacheKeys$(keys); + }); + }) + .last() + .map(function (node) { + return undefined; + }); }); }; - return MouseService; + Navigator.prototype._cacheKeys$ = function (keys) { + var _this = this; + var cacheNodes$ = keys + .map(function (key) { + return _this._graphService.cacheNode$(key); + }); + return Observable_1.Observable + .from(cacheNodes$) + .mergeAll(); + }; + Navigator.prototype._abortRequest = function (reason) { + if (this._requestSubscription != null) { + this._requestSubscription.unsubscribe(); + this._requestSubscription = null; + } + if (this._nodeRequestSubscription != null) { + this._nodeRequestSubscription.unsubscribe(); + this._nodeRequestSubscription = null; + } + if (this._request$ != null) { + if (!(this._request$.isStopped || this._request$.hasError)) { + this._request$.error(new Error_1.AbortMapillaryError("Request aborted by a subsequent request " + reason + ".")); + } + this._request$ = null; + } + }; + Navigator.prototype._makeRequest$ = function (node$) { + var _this = this; + var request$ = new ReplaySubject_1.ReplaySubject(1); + this._requestSubscription = request$ + .subscribe(undefined, function (e) { }); + this._request$ = request$; + this._nodeRequestSubscription = node$ + .subscribe(function (node) { + request$.next(node); + request$.complete(); + _this._request$ = null; + }, function (error) { + request$.error(error); + _this._request$ = null; + }); + return request$; + }; + Navigator.prototype._moveToKey$ = function (key) { + var _this = this; + this._keyRequested$.next(key); + return this._graphService.cacheNode$(key) + .do(function (node) { + _this._stateService.setNodes([node]); + _this._movedToKey$.next(node.key); + }) + .finally(function () { + _this._loadingService.stopLoading(_this._loadingName); + }); + }; + Navigator.prototype._trajectoryKeys$ = function () { + return this._stateService.currentState$ + .first() + .map(function (frame) { + return frame.state.trajectory + .map(function (node) { + return node.key; + }); + }); + }; + return Navigator; }()); -exports.MouseService = MouseService; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = MouseService; +exports.Navigator = Navigator; +exports.default = Navigator; -},{"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/distinctUntilChanged":53,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/merge":61,"rxjs/add/operator/mergeMap":63,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/switchMap":73,"rxjs/add/operator/withLatestFrom":76}],316:[function(require,module,exports){ -/// +},{"../API":289,"../Edge":291,"../Error":292,"../Graph":294,"../State":297,"../Viewer":301,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/ReplaySubject":32}],444:[function(require,module,exports){ "use strict"; -var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); +Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/observable/throw"); -require("rxjs/add/operator/do"); -require("rxjs/add/operator/finally"); -require("rxjs/add/operator/first"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/mergeMap"); -var API_1 = require("../API"); -var Graph_1 = require("../Graph"); -var Edge_1 = require("../Edge"); -var State_1 = require("../State"); var Viewer_1 = require("../Viewer"); -var Navigator = (function () { - function Navigator(clientId, apiV3, graphService, imageLoadingService, loadingService, stateService) { - this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId); - this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService(); - this._graphService = graphService != null ? - graphService : - new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService); - this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService(); - this._loadingName = "navigator"; - this._stateService = stateService != null ? stateService : new State_1.StateService(); - this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null); - this._movedToKey$ = new Subject_1.Subject(); - this._dirRequested$ = new BehaviorSubject_1.BehaviorSubject(null); - this._latLonRequested$ = new BehaviorSubject_1.BehaviorSubject(null); +var Observer = /** @class */ (function () { + function Observer(eventEmitter, navigator, container) { + var _this = this; + this._container = container; + this._eventEmitter = eventEmitter; + this._navigator = navigator; + this._projection = new Viewer_1.Projection(); + this._started = false; + this._navigable$ = new Subject_1.Subject(); + // navigable and loading should always emit, also when cover is activated. + this._navigable$ + .subscribe(function (navigable) { + _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable); + }); + this._navigator.loadingService.loading$ + .subscribe(function (loading) { + _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading); + }); } - Object.defineProperty(Navigator.prototype, "apiV3", { - get: function () { - return this._apiV3; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Navigator.prototype, "graphService", { + Object.defineProperty(Observer.prototype, "started", { get: function () { - return this._graphService; + return this._started; }, enumerable: true, configurable: true }); - Object.defineProperty(Navigator.prototype, "imageLoadingService", { + Object.defineProperty(Observer.prototype, "navigable$", { get: function () { - return this._imageLoadingService; + return this._navigable$; }, enumerable: true, configurable: true }); - Object.defineProperty(Navigator.prototype, "keyRequested$", { + Observer.prototype.projectBasic$ = function (basicPoint) { + var _this = this; + return Observable_1.Observable + .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .first() + .map(function (_a) { + var render = _a[0], transform = _a[1]; + var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform); + return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])]; + }); + }; + Observer.prototype.startEmit = function () { + var _this = this; + if (this._started) { + return; + } + this._started = true; + this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$ + .subscribe(function (node) { + _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node); + }); + this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$ + .switchMap(function (node) { + return node.sequenceEdges$; + }) + .subscribe(function (status) { + _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status); + }); + this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$ + .switchMap(function (node) { + return node.spatialEdges$; + }) + .subscribe(function (status) { + _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status); + }); + this._moveSubscription = Observable_1.Observable + .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$) + .map(function (values) { + return values[0] || values[1] || values[2]; + }) + .distinctUntilChanged() + .subscribe(function (started) { + if (started) { + _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null); + } + else { + _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null); + } + }); + this._bearingSubscription = this._container.renderService.bearing$ + .auditTime(100) + .distinctUntilChanged(function (b1, b2) { + return Math.abs(b2 - b1) < 1; + }) + .subscribe(function (bearing) { + _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing); + }); + var mouseMove$ = this._container.mouseService.active$ + .switchMap(function (active) { + return active ? + Observable_1.Observable.empty() : + _this._container.mouseService.mouseMove$; + }); + this._viewerMouseEventSubscription = Observable_1.Observable + .merge(this._mapMouseEvent$(Viewer_1.Viewer.click, this._container.mouseService.staticClick$), this._mapMouseEvent$(Viewer_1.Viewer.contextmenu, this._container.mouseService.contextMenu$), this._mapMouseEvent$(Viewer_1.Viewer.dblclick, this._container.mouseService.dblClick$), this._mapMouseEvent$(Viewer_1.Viewer.mousedown, this._container.mouseService.mouseDown$), this._mapMouseEvent$(Viewer_1.Viewer.mousemove, mouseMove$), this._mapMouseEvent$(Viewer_1.Viewer.mouseout, this._container.mouseService.mouseOut$), this._mapMouseEvent$(Viewer_1.Viewer.mouseover, this._container.mouseService.mouseOver$), this._mapMouseEvent$(Viewer_1.Viewer.mouseup, this._container.mouseService.mouseUp$)) + .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$) + .map(function (_a) { + var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3]; + var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform); + return { + basicPoint: unprojection.basicPoint, + latLon: unprojection.latLon, + originalEvent: event, + pixelPoint: unprojection.pixelPoint, + target: _this._eventEmitter, + type: type, + }; + }) + .subscribe(function (event) { + _this._eventEmitter.fire(event.type, event); + }); + }; + Observer.prototype.stopEmit = function () { + if (!this.started) { + return; + } + this._started = false; + this._bearingSubscription.unsubscribe(); + this._currentNodeSubscription.unsubscribe(); + this._moveSubscription.unsubscribe(); + this._sequenceEdgesSubscription.unsubscribe(); + this._spatialEdgesSubscription.unsubscribe(); + this._viewerMouseEventSubscription.unsubscribe(); + this._bearingSubscription = null; + this._currentNodeSubscription = null; + this._moveSubscription = null; + this._sequenceEdgesSubscription = null; + this._spatialEdgesSubscription = null; + this._viewerMouseEventSubscription = null; + }; + Observer.prototype.unproject$ = function (canvasPoint) { + var _this = this; + return Observable_1.Observable + .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$) + .first() + .map(function (_a) { + var render = _a[0], reference = _a[1], transform = _a[2]; + var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform); + return unprojection.latLon; + }); + }; + Observer.prototype.unprojectBasic$ = function (canvasPoint) { + var _this = this; + return Observable_1.Observable + .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$) + .first() + .map(function (_a) { + var render = _a[0], transform = _a[1]; + return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform); + }); + }; + Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) { + return mouseEvent$.map(function (event) { + return [type, event]; + }); + }; + return Observer; +}()); +exports.Observer = Observer; +exports.default = Observer; + +},{"../Viewer":301,"rxjs/Observable":29,"rxjs/Subject":34}],445:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("rxjs/Observable"); +var Subject_1 = require("rxjs/Subject"); +var Edge_1 = require("../Edge"); +var Graph_1 = require("../Graph"); +var PlayService = /** @class */ (function () { + function PlayService(graphService, stateService, graphCalculator) { + this._graphService = graphService; + this._stateService = stateService; + this._graphCalculator = !!graphCalculator ? graphCalculator : new Graph_1.GraphCalculator(); + this._directionSubject$ = new Subject_1.Subject(); + this._direction$ = this._directionSubject$ + .startWith(Edge_1.EdgeDirection.Next) + .publishReplay(1) + .refCount(); + this._direction$.subscribe(); + this._playing = false; + this._playingSubject$ = new Subject_1.Subject(); + this._playing$ = this._playingSubject$ + .startWith(this._playing) + .publishReplay(1) + .refCount(); + this._playing$.subscribe(); + this._speed = 0.5; + this._speedSubject$ = new Subject_1.Subject(); + this._speed$ = this._speedSubject$ + .startWith(this._speed) + .publishReplay(1) + .refCount(); + this._speed$.subscribe(); + this._nodesAhead = this._mapNodesAhead(this._mapSpeed(this._speed)); + this._bridging$ = null; + } + Object.defineProperty(PlayService.prototype, "playing", { get: function () { - return this._keyRequested$; + return this._playing; }, enumerable: true, configurable: true }); - Object.defineProperty(Navigator.prototype, "loadingService", { + Object.defineProperty(PlayService.prototype, "direction$", { get: function () { - return this._loadingService; + return this._direction$; }, enumerable: true, configurable: true }); - Object.defineProperty(Navigator.prototype, "movedToKey$", { + Object.defineProperty(PlayService.prototype, "playing$", { get: function () { - return this._movedToKey$; + return this._playing$; }, enumerable: true, configurable: true }); - Object.defineProperty(Navigator.prototype, "stateService", { + Object.defineProperty(PlayService.prototype, "speed$", { get: function () { - return this._stateService; + return this._speed$; }, enumerable: true, configurable: true }); - Navigator.prototype.moveToKey$ = function (key) { + PlayService.prototype.play = function () { var _this = this; - this.loadingService.startLoading(this._loadingName); - this._keyRequested$.next(key); - return this._graphService.cacheNode$(key) - .do(function (node) { - _this.stateService.setNodes([node]); - _this._movedToKey$.next(node.key); + if (this._playing) { + return; + } + this._stateService.cutNodes(); + var stateSpeed = this._setSpeed(this._speed); + this._stateService.setSpeed(stateSpeed); + this._graphModeSubscription = this._speed$ + .map(function (speed) { + return speed > 0.54 ? Graph_1.GraphMode.Sequence : Graph_1.GraphMode.Spatial; }) - .finally(function () { - _this.loadingService.stopLoading(_this._loadingName); + .distinctUntilChanged() + .subscribe(function (mode) { + _this._graphService.setGraphMode(mode); }); - }; - Navigator.prototype.moveDir$ = function (direction) { - var _this = this; - this.loadingService.startLoading(this._loadingName); - this._dirRequested$.next(direction); - return this.stateService.currentNode$ - .first() - .mergeMap(function (node) { + this._cacheSubscription = this._stateService.currentNode$ + .map(function (node) { + return [node.sequenceKey, node.key]; + }) + .distinctUntilChanged(undefined, function (_a) { + var sequenceKey = _a[0], nodeKey = _a[1]; + return sequenceKey; + }) + .combineLatest(this._graphService.graphMode$, this._direction$) + .switchMap(function (_a) { + var _b = _a[0], sequenceKey = _b[0], nodeKey = _b[1], mode = _a[1], direction = _a[2]; + if (direction !== Edge_1.EdgeDirection.Next && direction !== Edge_1.EdgeDirection.Prev) { + return Observable_1.Observable.of([undefined, direction]); + } + var sequence$ = (mode === Graph_1.GraphMode.Sequence ? + _this._graphService.cacheSequenceNodes$(sequenceKey, nodeKey) : + _this._graphService.cacheSequence$(sequenceKey)) + .retry(3) + .catch(function (error) { + console.error(error); + return Observable_1.Observable.of(undefined); + }); + return Observable_1.Observable + .combineLatest(sequence$, Observable_1.Observable.of(direction)); + }) + .switchMap(function (_a) { + var sequence = _a[0], direction = _a[1]; + if (sequence === undefined) { + return Observable_1.Observable.empty(); + } + var sequenceKeys = sequence.keys.slice(); + if (direction === Edge_1.EdgeDirection.Prev) { + sequenceKeys.reverse(); + } + return _this._stateService.currentState$ + .map(function (frame) { + return [frame.state.trajectory[frame.state.trajectory.length - 1].key, frame.state.nodesAhead]; + }) + .scan(function (_a, _b) { + var lastRequestKey = _a[0], previousRequestKeys = _a[1]; + var lastTrajectoryKey = _b[0], nodesAhead = _b[1]; + if (lastRequestKey === undefined) { + lastRequestKey = lastTrajectoryKey; + } + var lastIndex = sequenceKeys.length - 1; + if (nodesAhead >= _this._nodesAhead || sequenceKeys[lastIndex] === lastRequestKey) { + return [lastRequestKey, []]; + } + var current = sequenceKeys.indexOf(lastTrajectoryKey); + var start = sequenceKeys.indexOf(lastRequestKey) + 1; + var end = Math.min(lastIndex, current + _this._nodesAhead - nodesAhead) + 1; + if (end <= start) { + return [lastRequestKey, []]; + } + return [sequenceKeys[end - 1], sequenceKeys.slice(start, end)]; + }, [undefined, []]) + .mergeMap(function (_a) { + var lastRequestKey = _a[0], newRequestKeys = _a[1]; + return Observable_1.Observable.from(newRequestKeys); + }); + }) + .mergeMap(function (key) { + return _this._graphService.cacheNode$(key) + .catch(function () { + return Observable_1.Observable.empty(); + }); + }, 6) + .subscribe(); + this._playingSubscription = this._stateService.currentState$ + .filter(function (frame) { + return frame.state.nodesAhead < _this._nodesAhead; + }) + .distinctUntilChanged(undefined, function (frame) { + return frame.state.lastNode.key; + }) + .map(function (frame) { + var lastNode = frame.state.lastNode; + var trajectory = frame.state.trajectory; + var increasingTime = undefined; + for (var i = trajectory.length - 2; i >= 0; i--) { + var node = trajectory[i]; + if (node.sequenceKey !== lastNode.sequenceKey) { + break; + } + if (node.capturedAt !== lastNode.capturedAt) { + increasingTime = node.capturedAt < lastNode.capturedAt; + break; + } + } + return [frame.state.lastNode, increasingTime]; + }) + .withLatestFrom(this._direction$) + .switchMap(function (_a) { + var _b = _a[0], node = _b[0], increasingTime = _b[1], direction = _a[1]; return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ? node.sequenceEdges$ : node.spatialEdges$) - .first() - .map(function (status) { - for (var _i = 0, _a = status.edges; _i < _a.length; _i++) { - var edge = _a[_i]; - if (edge.data.direction === direction) { - return edge.to; + .first(function (status) { + return status.cached; + }) + .timeout(15000) + .zip(Observable_1.Observable.of(direction)) + .map(function (_a) { + var s = _a[0], d = _a[1]; + for (var _i = 0, _b = s.edges; _i < _b.length; _i++) { + var edge = _b[_i]; + if (edge.data.direction === d) { + return edge.to; + } + } + return null; + }) + .switchMap(function (key) { + return key != null ? + _this._graphService.cacheNode$(key) : + _this._bridge$(node, increasingTime) + .filter(function (n) { + return !!n; + }); + }); + }) + .subscribe(function (node) { + _this._stateService.appendNodes([node]); + }, function (error) { + console.error(error); + _this.stop(); + }); + this._clearSubscription = this._stateService.currentNode$ + .bufferCount(1, 10) + .subscribe(function (nodes) { + _this._stateService.clearPriorNodes(); + }); + this._setPlaying(true); + var currentLastNodes$ = this._stateService.currentState$ + .map(function (frame) { + return frame.state; + }) + .distinctUntilChanged(function (_a, _b) { + var kc1 = _a[0], kl1 = _a[1]; + var kc2 = _b[0], kl2 = _b[1]; + return kc1 === kc2 && kl1 === kl2; + }, function (state) { + return [state.currentNode.key, state.lastNode.key]; + }) + .filter(function (state) { + return state.currentNode.key === state.lastNode.key && + state.currentIndex === state.trajectory.length - 1; + }) + .map(function (state) { + return state.currentNode; + }); + this._stopSubscription = Observable_1.Observable + .combineLatest(currentLastNodes$, this._direction$) + .switchMap(function (_a) { + var node = _a[0], direction = _a[1]; + var edgeStatus$ = ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ? + node.sequenceEdges$ : + node.spatialEdges$) + .first(function (status) { + return status.cached; + }) + .timeout(15000) + .catch(function (error) { + console.error(error); + return Observable_1.Observable.of({ cached: false, edges: [] }); + }); + return Observable_1.Observable + .combineLatest(Observable_1.Observable.of(direction), edgeStatus$) + .map(function (_a) { + var d = _a[0], es = _a[1]; + for (var _i = 0, _b = es.edges; _i < _b.length; _i++) { + var edge = _b[_i]; + if (edge.data.direction === d) { + return true; } } - return null; + return false; }); }) - .mergeMap(function (directionKey) { - if (directionKey == null) { - _this.loadingService.stopLoading(_this._loadingName); - return Observable_1.Observable - .throw(new Error("Direction (" + direction + ") does not exist for current node.")); + .mergeMap(function (hasEdge) { + if (hasEdge || !_this._bridging$) { + return Observable_1.Observable.of(hasEdge); } - return _this.moveToKey$(directionKey); - }); + return _this._bridging$ + .map(function (node) { + return node != null; + }) + .catch(function (error) { + console.error(error); + return Observable_1.Observable.of(false); + }); + }) + .first(function (hasEdge) { + return !hasEdge; + }) + .subscribe(undefined, undefined, function () { _this.stop(); }); + if (this._stopSubscription.closed) { + this._stopSubscription = null; + } }; - Navigator.prototype.moveCloseTo$ = function (lat, lon) { + PlayService.prototype.setDirection = function (direction) { + this._directionSubject$.next(direction); + }; + PlayService.prototype.setSpeed = function (speed) { + speed = Math.max(0, Math.min(1, speed)); + if (speed === this._speed) { + return; + } + var stateSpeed = this._setSpeed(speed); + if (this._playing) { + this._stateService.setSpeed(stateSpeed); + } + this._speedSubject$.next(this._speed); + }; + PlayService.prototype.stop = function () { + if (!this._playing) { + return; + } + if (!!this._stopSubscription) { + if (!this._stopSubscription.closed) { + this._stopSubscription.unsubscribe(); + } + this._stopSubscription = null; + } + this._graphModeSubscription.unsubscribe(); + this._graphModeSubscription = null; + this._cacheSubscription.unsubscribe(); + this._cacheSubscription = null; + this._playingSubscription.unsubscribe(); + this._playingSubscription = null; + this._clearSubscription.unsubscribe(); + this._clearSubscription = null; + this._stateService.setSpeed(1); + this._stateService.cutNodes(); + this._graphService.setGraphMode(Graph_1.GraphMode.Spatial); + this._setPlaying(false); + }; + PlayService.prototype._bridge$ = function (node, increasingTime) { var _this = this; - this.loadingService.startLoading(this._loadingName); - this._latLonRequested$.next({ lat: lat, lon: lon }); - return this.apiV3.imageCloseTo$(lat, lon) - .mergeMap(function (fullNode) { - if (fullNode == null) { - _this.loadingService.stopLoading(_this._loadingName); - return Observable_1.Observable - .throw(new Error("No image found close to lat " + lat + ", lon " + lon + ".")); + if (increasingTime === undefined) { + return Observable_1.Observable.of(null); + } + var boundingBox = this._graphCalculator.boundingBoxCorners(node.latLon, 25); + this._bridging$ = this._graphService.cacheBoundingBox$(boundingBox[0], boundingBox[1]) + .mergeMap(function (nodes) { + var nextNode = null; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var n = nodes_1[_i]; + if (n.sequenceKey === node.sequenceKey || + !n.cameraUuid || + n.cameraUuid !== node.cameraUuid || + n.capturedAt === node.capturedAt || + n.capturedAt > node.capturedAt !== increasingTime) { + continue; + } + var delta = Math.abs(n.capturedAt - node.capturedAt); + if (delta > 15000) { + continue; + } + if (!nextNode || delta < Math.abs(nextNode.capturedAt - node.capturedAt)) { + nextNode = n; + } } - return _this.moveToKey$(fullNode.key); - }); + return !!nextNode ? + _this._graphService.cacheNode$(nextNode.key) : + Observable_1.Observable.of(null); + }) + .finally(function () { + _this._bridging$ = null; + }) + .publish() + .refCount(); + return this._bridging$; }; - return Navigator; + PlayService.prototype._mapSpeed = function (speed) { + var x = 2 * speed - 1; + return Math.pow(10, x) - 0.2 * x; + }; + PlayService.prototype._mapNodesAhead = function (stateSpeed) { + return Math.round(Math.max(10, Math.min(50, 8 + 6 * stateSpeed))); + }; + PlayService.prototype._setPlaying = function (playing) { + this._playing = playing; + this._playingSubject$.next(playing); + }; + PlayService.prototype._setSpeed = function (speed) { + this._speed = speed; + var stateSpeed = this._mapSpeed(this._speed); + this._nodesAhead = this._mapNodesAhead(stateSpeed); + return stateSpeed; + }; + return PlayService; }()); -exports.Navigator = Navigator; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Navigator; +exports.PlayService = PlayService; +exports.default = PlayService; -},{"../API":206,"../Edge":208,"../Graph":211,"../State":214,"../Viewer":216,"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/throw":45,"rxjs/add/operator/do":54,"rxjs/add/operator/finally":57,"rxjs/add/operator/first":58,"rxjs/add/operator/map":60,"rxjs/add/operator/mergeMap":63}],317:[function(require,module,exports){ +},{"../Edge":291,"../Graph":294,"rxjs/Observable":29,"rxjs/Subject":34}],446:[function(require,module,exports){ "use strict"; -(function (SpriteAlignment) { - SpriteAlignment[SpriteAlignment["Center"] = 0] = "Center"; - SpriteAlignment[SpriteAlignment["Start"] = 1] = "Start"; - SpriteAlignment[SpriteAlignment["End"] = 2] = "End"; -})(exports.SpriteAlignment || (exports.SpriteAlignment = {})); -var SpriteAlignment = exports.SpriteAlignment; +/// Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SpriteAlignment; +var THREE = require("three"); +var Geo_1 = require("../Geo"); +var Projection = /** @class */ (function () { + function Projection(geoCoords, viewportCoords) { + this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords(); + this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords(); + } + Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) { + return this._viewportCoords + .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective); + }; + Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) { + var basicPoint = this._viewportCoords + .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective); + if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) { + basicPoint = null; + } + return basicPoint; + }; + Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) { + var pixelPoint = this._viewportCoords.canvasPosition(event, container); + return this.canvasToUnprojection(pixelPoint, container, render, reference, transform); + }; + Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) { + var canvasX = canvasPoint[0]; + var canvasY = canvasPoint[1]; + var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1]; + var point3d = new THREE.Vector3(viewportX, viewportY, 1) + .unproject(render.perspective); + var basicPoint = transform.projectBasic(point3d.toArray()); + if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) { + basicPoint = null; + } + var direction3d = point3d.clone().sub(render.camera.position).normalize(); + var dist = -2 / direction3d.z; + var latLon = null; + if (dist > 0 && dist < 100 && !!basicPoint) { + var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position); + var latLonArray = this._geoCoords + .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt) + .slice(0, 2); + latLon = { lat: latLonArray[0], lon: latLonArray[1] }; + } + var unprojection = { + basicPoint: basicPoint, + latLon: latLon, + pixelPoint: [canvasX, canvasY], + }; + return unprojection; + }; + return Projection; +}()); +exports.Projection = Projection; +exports.default = Projection; -},{}],318:[function(require,module,exports){ -/// +},{"../Geo":293,"three":240}],447:[function(require,module,exports){ "use strict"; +/// +Object.defineProperty(exports, "__esModule", { value: true }); var THREE = require("three"); var vd = require("virtual-dom"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/publishReplay"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/startWith"); var Viewer_1 = require("../Viewer"); -var SpriteAtlas = (function () { +var SpriteAtlas = /** @class */ (function () { function SpriteAtlas() { } Object.defineProperty(SpriteAtlas.prototype, "json", { @@ -32711,15 +47043,12 @@ var SpriteAtlas = (function () { var material = new THREE.SpriteMaterial({ map: texture }); return new THREE.Sprite(material); }; - SpriteAtlas.prototype.getDOMSprite = function (name, horizontalAlign, verticalAlign) { + SpriteAtlas.prototype.getDOMSprite = function (name, float) { if (!this.loaded) { throw new Error("Sprites cannot be retrieved before the atlas is loaded."); } - if (horizontalAlign == null) { - horizontalAlign = Viewer_1.SpriteAlignment.Start; - } - if (verticalAlign == null) { - verticalAlign = Viewer_1.SpriteAlignment.Start; + if (float == null) { + float = Viewer_1.Alignment.Center; } var definition = this._json[name]; if (!definition) { @@ -32734,27 +47063,37 @@ var SpriteAtlas = (function () { var top = -definition.y; var height = this._image.height; var width = this._image.width; - switch (horizontalAlign) { - case Viewer_1.SpriteAlignment.Center: + switch (float) { + case Viewer_1.Alignment.Bottom: + case Viewer_1.Alignment.Center: + case Viewer_1.Alignment.Top: left -= definition.width / 2; break; - case Viewer_1.SpriteAlignment.End: + case Viewer_1.Alignment.BottomLeft: + case Viewer_1.Alignment.Left: + case Viewer_1.Alignment.TopLeft: left -= definition.width; break; - case Viewer_1.SpriteAlignment.Start: - break; + case Viewer_1.Alignment.BottomRight: + case Viewer_1.Alignment.Right: + case Viewer_1.Alignment.TopRight: default: break; } - switch (verticalAlign) { - case Viewer_1.SpriteAlignment.Center: + switch (float) { + case Viewer_1.Alignment.Center: + case Viewer_1.Alignment.Left: + case Viewer_1.Alignment.Right: top -= definition.height / 2; break; - case Viewer_1.SpriteAlignment.End: + case Viewer_1.Alignment.Top: + case Viewer_1.Alignment.TopLeft: + case Viewer_1.Alignment.TopRight: top -= definition.height; break; - case Viewer_1.SpriteAlignment.Start: - break; + case Viewer_1.Alignment.Bottom: + case Viewer_1.Alignment.BottomLeft: + case Viewer_1.Alignment.BottomRight: default: break; } @@ -32782,7 +47121,7 @@ var SpriteAtlas = (function () { }; return SpriteAtlas; }()); -var SpriteService = (function () { +var SpriteService = /** @class */ (function () { function SpriteService(sprite) { var _this = this; this._retina = window.devicePixelRatio > 1; @@ -32796,7 +47135,7 @@ var SpriteService = (function () { }, new SpriteAtlas()) .publishReplay(1) .refCount(); - this._spriteAtlas$.subscribe(); + this._spriteAtlas$.subscribe(function () { }); if (sprite == null) { return; } @@ -32844,89 +47183,62 @@ var SpriteService = (function () { return SpriteService; }()); exports.SpriteService = SpriteService; -Object.defineProperty(exports, "__esModule", { value: true }); exports.default = SpriteService; -},{"../Viewer":216,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":67,"rxjs/add/operator/scan":68,"rxjs/add/operator/startWith":72,"three":157,"virtual-dom":163}],319:[function(require,module,exports){ -/// +},{"../Viewer":301,"rxjs/Subject":34,"three":240,"virtual-dom":246}],448:[function(require,module,exports){ "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var BehaviorSubject_1 = require("rxjs/BehaviorSubject"); var Observable_1 = require("rxjs/Observable"); var Subject_1 = require("rxjs/Subject"); -require("rxjs/add/operator/filter"); -require("rxjs/add/operator/map"); -require("rxjs/add/operator/merge"); -require("rxjs/add/operator/scan"); -require("rxjs/add/operator/switchMap"); -var TouchMove = (function () { - function TouchMove(touch) { - this.movementX = 0; - this.movementY = 0; - if (touch == null) { - return; - } - this.identifier = touch.identifier; - this.clientX = touch.clientX; - this.clientY = touch.clientY; - this.pageX = touch.pageX; - this.pageY = touch.pageY; - this.screenX = touch.screenX; - this.screenY = touch.screenY; - this.target = touch.target; - } - return TouchMove; -}()); -exports.TouchMove = TouchMove; -var TouchService = (function () { - function TouchService(element) { +var TouchService = /** @class */ (function () { + function TouchService(canvasContainer, domContainer) { var _this = this; - this._element = element; - this._touchStart$ = Observable_1.Observable.fromEvent(element, "touchstart"); - this._touchMove$ = Observable_1.Observable.fromEvent(element, "touchmove"); - this._touchEnd$ = Observable_1.Observable.fromEvent(element, "touchend"); - this._touchCancel$ = Observable_1.Observable.fromEvent(element, "touchcancel"); - this._preventTouchMoveOperation$ = new Subject_1.Subject(); - this._preventTouchMove$ = new Subject_1.Subject(); - this._preventTouchMoveOperation$ - .scan(function (prevent, operation) { - return operation(prevent); - }, true) - .subscribe(); - this._preventTouchMove$ - .map(function (prevent) { - return function (previous) { - return prevent; - }; + this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false); + this._active$ = this._activeSubject$ + .distinctUntilChanged() + .publishReplay(1) + .refCount(); + Observable_1.Observable.fromEvent(domContainer, "touchmove") + .subscribe(function (event) { + event.preventDefault(); + }); + this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart"); + this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove"); + this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend"); + this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel"); + var tapStart$ = this._touchStart$ + .filter(function (te) { + return te.touches.length === 1 && te.targetTouches.length === 1; }) - .subscribe(this._preventTouchMoveOperation$); - this._touchMove$ - .map(function (te) { - return function (prevent) { - if (prevent) { - te.preventDefault(); - } - return prevent; - }; + .share(); + this._doubleTap$ = tapStart$ + .bufferWhen(function () { + return tapStart$ + .first() + .switchMap(function (event) { + return Observable_1.Observable + .timer(300) + .merge(tapStart$) + .take(1); + }); }) - .subscribe(this._preventTouchMoveOperation$); - this._singleTouchMoveOperation$ = new Subject_1.Subject(); - this._singleTouchMove$ = this._singleTouchMoveOperation$ - .scan(function (touch, operation) { - return operation(touch); - }, new TouchMove()); - this._touchMove$ + .filter(function (events) { + return events.length === 2; + }) + .map(function (events) { + return events[events.length - 1]; + }) + .share(); + this._doubleTap$ + .subscribe(function (event) { + event.preventDefault(); + }); + this._singleTouchMove$ = this._touchMove$ .filter(function (te) { return te.touches.length === 1 && te.targetTouches.length === 1; }) - .map(function (te) { - return function (previous) { - var touch = te.touches[0]; - var current = new TouchMove(touch); - current.movementX = touch.pageX - previous.pageX; - current.movementY = touch.pageY - previous.pageY; - return current; - }; - }) - .subscribe(this._singleTouchMoveOperation$); + .share(); var singleTouchStart$ = Observable_1.Observable .merge(this._touchStart$, this._touchEnd$, this._touchCancel$) .filter(function (te) { @@ -32942,7 +47254,19 @@ var TouchService = (function () { .filter(function (te) { return te.touches.length === 0; }); - this._singleTouch$ = singleTouchStart$ + this._singleTouchDragStart$ = singleTouchStart$ + .mergeMap(function (e) { + return _this._singleTouchMove$ + .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$)) + .take(1); + }); + this._singleTouchDragEnd$ = singleTouchStart$ + .mergeMap(function (e) { + return Observable_1.Observable + .merge(touchStop$, multipleTouchStart$) + .first(); + }); + this._singleTouchDrag$ = singleTouchStart$ .switchMap(function (te) { return _this._singleTouchMove$ .skip(1) @@ -32951,11 +47275,11 @@ var TouchService = (function () { }); var touchesChanged$ = Observable_1.Observable .merge(this._touchStart$, this._touchEnd$, this._touchCancel$); - var pinchStart$ = touchesChanged$ + this._pinchStart$ = touchesChanged$ .filter(function (te) { return te.touches.length === 2 && te.targetTouches.length === 2; }); - var pinchStop$ = touchesChanged$ + this._pinchEnd$ = touchesChanged$ .filter(function (te) { return te.touches.length !== 2 || te.targetTouches.length !== 2; }); @@ -32964,18 +47288,19 @@ var TouchService = (function () { .scan(function (pinch, operation) { return operation(pinch); }, { - centerClientX: 0, - centerClientY: 0, - centerPageX: 0, - centerPageY: 0, - centerScreenX: 0, - centerScreenY: 0, changeX: 0, changeY: 0, + clientX: 0, + clientY: 0, distance: 0, distanceChange: 0, distanceX: 0, distanceY: 0, + originalEvent: null, + pageX: 0, + pageY: 0, + screenX: 0, + screenY: 0, touch1: null, touch2: null, }); @@ -33004,18 +47329,19 @@ var TouchService = (function () { var changeX = distanceX - previous.distanceX; var changeY = distanceY - previous.distanceY; var current = { - centerClientX: centerClientX, - centerClientY: centerClientY, - centerPageX: centerPageX, - centerPageY: centerPageY, - centerScreenX: centerScreenX, - centerScreenY: centerScreenY, changeX: changeX, changeY: changeY, + clientX: centerClientX, + clientY: centerClientY, distance: distance, distanceChange: distanceChange, distanceX: distanceX, distanceY: distanceY, + originalEvent: te, + pageX: centerPageX, + pageY: centerPageY, + screenX: centerScreenX, + screenY: centerScreenY, touch1: touch1, touch2: touch2, }; @@ -33023,13 +47349,34 @@ var TouchService = (function () { }; }) .subscribe(this._pinchOperation$); - this._pinchChange$ = pinchStart$ + this._pinchChange$ = this._pinchStart$ .switchMap(function (te) { return _this._pinch$ .skip(1) - .takeUntil(pinchStop$); + .takeUntil(_this._pinchEnd$); }); } + Object.defineProperty(TouchService.prototype, "active$", { + get: function () { + return this._active$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TouchService.prototype, "activate$", { + get: function () { + return this._activeSubject$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TouchService.prototype, "doubleTap$", { + get: function () { + return this._doubleTap$; + }, + enumerable: true, + configurable: true + }); Object.defineProperty(TouchService.prototype, "touchStart$", { get: function () { return this._touchStart$; @@ -33058,9 +47405,23 @@ var TouchService = (function () { enumerable: true, configurable: true }); - Object.defineProperty(TouchService.prototype, "singleTouchMove$", { + Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", { + get: function () { + return this._singleTouchDragStart$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TouchService.prototype, "singleTouchDrag$", { + get: function () { + return this._singleTouchDrag$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", { get: function () { - return this._singleTouch$; + return this._singleTouchDragEnd$; }, enumerable: true, configurable: true @@ -33072,9 +47433,16 @@ var TouchService = (function () { enumerable: true, configurable: true }); - Object.defineProperty(TouchService.prototype, "preventDefaultTouchMove$", { + Object.defineProperty(TouchService.prototype, "pinchStart$", { + get: function () { + return this._pinchStart$; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TouchService.prototype, "pinchEnd$", { get: function () { - return this._preventTouchMove$; + return this._pinchEnd$; }, enumerable: true, configurable: true @@ -33083,59 +47451,383 @@ var TouchService = (function () { }()); exports.TouchService = TouchService; -},{"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/filter":56,"rxjs/add/operator/map":60,"rxjs/add/operator/merge":61,"rxjs/add/operator/scan":68,"rxjs/add/operator/switchMap":73}],320:[function(require,module,exports){ -/// +},{"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34}],449:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); var when = require("when"); +require("rxjs/add/observable/combineLatest"); +require("rxjs/add/observable/concat"); +require("rxjs/add/observable/defer"); +require("rxjs/add/observable/empty"); +require("rxjs/add/observable/merge"); +require("rxjs/add/observable/from"); +require("rxjs/add/observable/fromEvent"); +require("rxjs/add/observable/fromPromise"); +require("rxjs/add/observable/of"); +require("rxjs/add/observable/throw"); +require("rxjs/add/observable/timer"); +require("rxjs/add/observable/zip"); +require("rxjs/add/operator/auditTime"); +require("rxjs/add/operator/buffer"); +require("rxjs/add/operator/bufferCount"); +require("rxjs/add/operator/bufferWhen"); +require("rxjs/add/operator/catch"); +require("rxjs/add/operator/combineLatest"); +require("rxjs/add/operator/concat"); +require("rxjs/add/operator/count"); +require("rxjs/add/operator/debounceTime"); +require("rxjs/add/operator/delay"); +require("rxjs/add/operator/distinct"); +require("rxjs/add/operator/distinctUntilChanged"); +require("rxjs/add/operator/do"); +require("rxjs/add/operator/expand"); +require("rxjs/add/operator/filter"); +require("rxjs/add/operator/finally"); +require("rxjs/add/operator/first"); +require("rxjs/add/operator/last"); +require("rxjs/add/operator/map"); +require("rxjs/add/operator/merge"); +require("rxjs/add/operator/mergeMap"); +require("rxjs/add/operator/mergeAll"); +require("rxjs/add/operator/pairwise"); +require("rxjs/add/operator/pluck"); +require("rxjs/add/operator/publish"); +require("rxjs/add/operator/publishReplay"); +require("rxjs/add/operator/reduce"); +require("rxjs/add/operator/retry"); +require("rxjs/add/operator/sample"); +require("rxjs/add/operator/scan"); +require("rxjs/add/operator/share"); +require("rxjs/add/operator/skip"); +require("rxjs/add/operator/skipUntil"); +require("rxjs/add/operator/skipWhile"); +require("rxjs/add/operator/startWith"); +require("rxjs/add/operator/switchMap"); +require("rxjs/add/operator/take"); +require("rxjs/add/operator/takeUntil"); +require("rxjs/add/operator/takeWhile"); +require("rxjs/add/operator/timeout"); +require("rxjs/add/operator/withLatestFrom"); +require("rxjs/add/operator/zip"); +var Observable_1 = require("rxjs/Observable"); var Viewer_1 = require("../Viewer"); var Utils_1 = require("../Utils"); /** * @class Viewer * - * @classdesc The Viewer object represents the navigable photo viewer. - * Create a Viewer by specifying a container, client ID, photo key and + * @classdesc The Viewer object represents the navigable image viewer. + * Create a Viewer by specifying a container, client ID, image key and * other options. The viewer exposes methods and events for programmatic * interaction. + * + * The viewer works with a few different coordinate systems. + * + * Container pixel coordinates + * + * Pixel coordinates are coordinates on the viewer container. The origin is + * in the top left corner of the container. The axes are + * directed according to the following for a viewer container with a width + * of 640 pixels and height of 480 pixels. + * + * ``` + * (0,0) (640, 0) + * +------------------------> + * | + * | + * | + * v + + * (0, 480) (640, 480) + * ``` + * + * Basic image coordinates + * + * Basic image coordinates represents points in the original image adjusted for + * orientation. They range from 0 to 1 on both axes. The origin is in the top left + * corner of the image and the axes are directed + * according to the following for all image types. + * + * ``` + * (0,0) (1, 0) + * +------------------------> + * | + * | + * | + * v + + * (0, 1) (1, 1) + * ``` + * + * For every camera viewing direction it is possible to convert between these + * two coordinate systems for the current node. The image can be panned and + * zoomed independently of the size of the viewer container resulting in + * different conversion results for different viewing directions. */ -var Viewer = (function (_super) { +var Viewer = /** @class */ (function (_super) { __extends(Viewer, _super); /** - * Create a new viewer instance. + * Create a new viewer instance. + * + * @description It is possible to initialize the viewer with or + * without a key. + * + * When you want to show a specific image in the viewer from + * the start you should initialize it with a key. + * + * When you do not know the first image key at implementation + * time, e.g. in a map-viewer application you should initialize + * the viewer without a key and call `moveToKey` instead. + * + * When initializing with a key the viewer is bound to that key + * until the node for that key has been successfully loaded. + * Also, a cover with the image of the key will be shown. + * If the data for that key can not be loaded because the key is + * faulty or other errors occur it is not possible to navigate + * to another key because the viewer is not navigable. The viewer + * becomes navigable when the data for the key has been loaded and + * the image is shown in the viewer. This way of initializing + * the viewer is mostly for embedding in blog posts and similar + * where one wants to show a specific image initially. + * + * If the viewer is initialized without a key (with null or + * undefined) it is not bound to any particular key and it is + * possible to move to any key with `viewer.moveToKey("")`. + * If the first move to a key fails it is possible to move to another + * key. The viewer will show a black background until a move + * succeeds. This way of intitializing is suited for a map-viewer + * application when the initial key is not known at implementation + * time. + * + * @param {string} id - Required `id` of a DOM element which will + * be transformed into the viewer. + * @param {string} clientId - Required `Mapillary API ClientID`. Can + * be obtained from https://www.mapillary.com/app/settings/developers. + * @param {string} key - Optional `image-key` to start from. The key + * can be any Mapillary image. If a key is provided the viewer is + * bound to that key until it has been fully loaded. If null is provided + * no image is loaded at viewer initialization and the viewer is not + * bound to any particular key. Any image can then be navigated to + * with e.g. `viewer.moveToKey("")`. + * @param {IViewerOptions} options - Optional configuration object + * specifing Viewer's and the components' initial setup. + * @param {string} token - Optional bearer token for API requests of + * protected resources. + * + * @example + * ``` + * var viewer = new Mapillary.Viewer("", "", ""); + * ``` + */ + function Viewer(id, clientId, key, options, token) { + var _this = _super.call(this) || this; + options = options != null ? options : {}; + Utils_1.Settings.setOptions(options); + Utils_1.Urls.setOptions(options.url); + _this._navigator = new Viewer_1.Navigator(clientId, options, token); + _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options); + _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container); + _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component); + return _this; + } + Object.defineProperty(Viewer.prototype, "isNavigable", { + /** + * Return a boolean indicating if the viewer is in a navigable state. + * + * @description The navigable state indicates if the viewer supports + * moving, i.e. calling the {@link moveToKey}, {@link moveDir`} + * and {@link moveCloseTo} methods or changing the authentication state, + * i.e. calling {@link setAuthToken}. The viewer will not be in a navigable + * state if the cover is activated and the viewer has been supplied a key. + * When the cover is deactivated or the viewer is activated without being + * supplied a key it will be navigable. + * + * @returns {boolean} Boolean indicating whether the viewer is navigable. + */ + get: function () { + return this._componentController.navigable; + }, + enumerable: true, + configurable: true + }); + /** + * Activate a component. + * + * @param {string} name - Name of the component which will become active. + * + * @example + * ``` + * viewer.activateComponent("marker"); + * ``` + */ + Viewer.prototype.activateComponent = function (name) { + this._componentController.activate(name); + }; + /** + * Activate the cover (deactivates all other components). + */ + Viewer.prototype.activateCover = function () { + this._componentController.activateCover(); + }; + /** + * Deactivate a component. * - * @param {string} id - required `id` of an DOM element which will - * be transformed into the viewer. - * @param {string} clientId - required `Mapillary API ClientID`, can - * be obtained from https://www.mapillary.com/app/settings/developers. - * @param {string} key - optional `photoId` to start from, can be any - * Mapillary photo, if null no image is loaded. - * @param {IViewerOptions} options - optional configuration object - * specifing Viewer's initial setup. + * @param {string} name - Name of component which become inactive. + * + * @example + * ``` + * viewer.deactivateComponent("mouse"); + * ``` */ - function Viewer(id, clientId, key, options) { - _super.call(this); - options = options != null ? options : {}; - Utils_1.Settings.setOptions(options); - this._navigator = new Viewer_1.Navigator(clientId); - this._container = new Viewer_1.Container(id, this._navigator.stateService, options); - this._eventLauncher = new Viewer_1.EventLauncher(this, this._navigator, this._container); - this._componentController = new Viewer_1.ComponentController(this._container, this._navigator, key, options.component); - } + Viewer.prototype.deactivateComponent = function (name) { + this._componentController.deactivate(name); + }; + /** + * Deactivate the cover (activates all components marked as active). + */ + Viewer.prototype.deactivateCover = function () { + this._componentController.deactivateCover(); + }; + /** + * Get the bearing of the current viewer camera. + * + * @description The bearing depends on how the camera + * is currently rotated and does not correspond + * to the compass angle of the current node if the view + * has been panned. + * + * Bearing is measured in degrees clockwise with respect to + * north. + * + * @returns {Promise} Promise to the bearing + * of the current viewer camera. + * + * @example + * ``` + * viewer.getBearing().then((b) => { console.log(b); }); + * ``` + */ + Viewer.prototype.getBearing = function () { + var _this = this; + return when.promise(function (resolve, reject) { + _this._container.renderService.bearing$ + .first() + .subscribe(function (bearing) { + resolve(bearing); + }, function (error) { + reject(error); + }); + }); + }; + /** + * Get the basic coordinates of the current image that is + * at the center of the viewport. + * + * @description Basic coordinates are 2D coordinates on the [0, 1] interval + * and have the origin point, (0, 0), at the top left corner and the + * maximum value, (1, 1), at the bottom right corner of the original + * image. + * + * @returns {Promise} Promise to the basic coordinates + * of the current image at the center for the viewport. + * + * @example + * ``` + * viewer.getCenter().then((c) => { console.log(c); }); + * ``` + */ + Viewer.prototype.getCenter = function () { + var _this = this; + return when.promise(function (resolve, reject) { + _this._navigator.stateService.getCenter() + .subscribe(function (center) { + resolve(center); + }, function (error) { + reject(error); + }); + }); + }; + /** + * Get a component. + * + * @param {string} name - Name of component. + * @returns {Component} The requested component. + * + * @example + * ``` + * var mouseComponent = viewer.getComponent("mouse"); + * ``` + */ + Viewer.prototype.getComponent = function (name) { + return this._componentController.get(name); + }; + /** + * Returns the viewer's containing HTML element. + * + * @returns {HTMLElement} The viewer's container. + */ + Viewer.prototype.getContainer = function () { + return this._container.element; + }; + /** + * Get the image's current zoom level. + * + * @returns {Promise} Promise to the viewers's current + * zoom level. + * + * @example + * ``` + * viewer.getZoom().then((z) => { console.log(z); }); + * ``` + */ + Viewer.prototype.getZoom = function () { + var _this = this; + return when.promise(function (resolve, reject) { + _this._navigator.stateService.getZoom() + .subscribe(function (zoom) { + resolve(zoom); + }, function (error) { + reject(error); + }); + }); + }; /** - * Navigate to a given photo key. + * Move close to given latitude and longitude. + * + * @description Because the method propagates IO errors, these potential errors + * need to be handled by the method caller (see example). * - * @param {string} key - A valid Mapillary photo key. + * @param {Number} lat - Latitude, in degrees. + * @param {Number} lon - Longitude, in degrees. * @returns {Promise} Promise to the node that was navigated to. + * @throws {Error} If no nodes exist close to provided latitude + * longitude. * @throws {Error} Propagates any IO errors to the caller. + * @throws {Error} When viewer is not navigable. + * @throws {AbortMapillaryError} When a subsequent move request is made + * before the move close to call has completed. + * + * @example + * ``` + * viewer.moveCloseTo(0, 0).then( + * (n) => { console.log(n); }, + * (e) => { console.error(e); }); + * ``` */ - Viewer.prototype.moveToKey = function (key) { - var _this = this; + Viewer.prototype.moveCloseTo = function (lat, lon) { + var moveCloseTo$ = this.isNavigable ? + this._navigator.moveCloseTo$(lat, lon) : + Observable_1.Observable.throw(new Error("Calling moveCloseTo is not supported when viewer is not navigable.")); return when.promise(function (resolve, reject) { - _this._navigator.moveToKey$(key).subscribe(function (node) { + moveCloseTo$.subscribe(function (node) { resolve(node); }, function (error) { reject(error); @@ -33152,13 +47844,23 @@ var Viewer = (function (_super) { * @throws {Error} If the current node does not have the edge direction * or the edges has not yet been cached. * @throws {Error} Propagates any IO errors to the caller. + * @throws {Error} When viewer is not navigable. + * @throws {AbortMapillaryError} When a subsequent move request is made + * before the move dir call has completed. * - * @example `viewer.moveDir(Mapillary.EdgeDirection.Next);` + * @example + * ``` + * viewer.moveDir(Mapillary.EdgeDirection.Next).then( + * (n) => { console.log(n); }, + * (e) => { console.error(e); }); + * ``` */ Viewer.prototype.moveDir = function (dir) { - var _this = this; + var moveDir$ = this.isNavigable ? + this._navigator.moveDir$(dir) : + Observable_1.Observable.throw(new Error("Calling moveDir is not supported when viewer is not navigable.")); return when.promise(function (resolve, reject) { - _this._navigator.moveDir$(dir).subscribe(function (node) { + moveDir$.subscribe(function (node) { resolve(node); }, function (error) { reject(error); @@ -33166,167 +47868,389 @@ var Viewer = (function (_super) { }); }; /** - * Move close to given latitude and longitude. + * Navigate to a given image key. * - * @param {Number} lat - Latitude, in degrees. - * @param {Number} lon - Longitude, in degrees. + * @param {string} key - A valid Mapillary image key. * @returns {Promise} Promise to the node that was navigated to. - * @throws {Error} If no nodes exist close to provided latitude - * longitude. * @throws {Error} Propagates any IO errors to the caller. + * @throws {Error} When viewer is not navigable. + * @throws {AbortMapillaryError} When a subsequent move request is made + * before the move to key call has completed. + * + * @example + * ``` + * viewer.moveToKey("").then( + * (n) => { console.log(n); }, + * (e) => { console.error(e); }); + * ``` */ - Viewer.prototype.moveCloseTo = function (lat, lon) { - var _this = this; + Viewer.prototype.moveToKey = function (key) { + var moveToKey$ = this.isNavigable ? + this._navigator.moveToKey$(key) : + Observable_1.Observable.throw(new Error("Calling moveToKey is not supported when viewer is not navigable.")); return when.promise(function (resolve, reject) { - _this._navigator.moveCloseTo$(lat, lon).subscribe(function (node) { + moveToKey$.subscribe(function (node) { resolve(node); }, function (error) { reject(error); }); }); }; + /** + * Project basic image coordinates for the current node to canvas pixel + * coordinates. + * + * @description The basic image coordinates may not always correspond to a + * pixel point that lies in the visible area of the viewer container. + * + * @param {Array} basicPoint - Basic images coordinates to project. + * @returns {Promise>} Promise to the pixel coordinates corresponding + * to the basic image point. + * + * @example + * ``` + * viewer.projectFromBasic([0.3, 0.7]) + * .then((pixelPoint) => { console.log(pixelPoint); }); + * ``` + */ + Viewer.prototype.projectFromBasic = function (basicPoint) { + var _this = this; + return when.promise(function (resolve, reject) { + _this._observer.projectBasic$(basicPoint) + .subscribe(function (pixelPoint) { + resolve(pixelPoint); + }, function (error) { + reject(error); + }); + }); + }; /** * Detect the viewer's new width and height and resize it. * * @description The components will also detect the viewer's * new size and resize their rendered elements if needed. + * + * @example + * ``` + * viewer.resize(); + * ``` */ Viewer.prototype.resize = function () { this._container.renderService.resize$.next(null); this._componentController.resize(); }; /** - * Set the viewer's render mode. + * Set a bearer token for authenticated API requests of + * protected resources. * - * @param {RenderMode} renderMode - Render mode. + * @description When the supplied token is null or undefined, + * any previously set bearer token will be cleared and the + * viewer will make unauthenticated requests. + * + * Calling setAuthToken aborts all outstanding move requests. + * The promises of those move requests will be rejected with a + * {@link AbortMapillaryError} the rejections need to be caught. * - * @example `viewer.setRenderMode(Mapillary.RenderMode.Letterbox);` + * Calling setAuthToken also resets the complete viewer cache + * so it should not be called repeatedly. + * + * @param {string} [token] token - Bearer token. + * @returns {Promise} Promise that resolves after token + * is set. + * + * @throws {Error} When viewer is not navigable. + * + * @example + * ``` + * viewer.setAuthToken("") + * .then(() => { console.log("token set"); }); + * ``` */ - Viewer.prototype.setRenderMode = function (renderMode) { - this._container.renderService.renderMode$.next(renderMode); + Viewer.prototype.setAuthToken = function (token) { + var setToken$ = this.isNavigable ? + this._navigator.setToken$(token) : + Observable_1.Observable.throw(new Error("Calling setAuthToken is not supported when viewer is not navigable.")); + return when.promise(function (resolve, reject) { + setToken$ + .subscribe(function () { + resolve(undefined); + }, function (error) { + reject(error); + }); + }); }; /** - * Activate a component. + * Set the basic coordinates of the current image to be in the + * center of the viewport. * - * @param {string} name - Name of the component which will become active. + * @description Basic coordinates are 2D coordinates on the [0, 1] interval + * and has the origin point, (0, 0), at the top left corner and the + * maximum value, (1, 1), at the bottom right corner of the original + * image. + * + * @param {number[]} The basic coordinates of the current + * image to be at the center for the viewport. + * + * @example + * ``` + * viewer.setCenter([0.5, 0.5]); + * ``` */ - Viewer.prototype.activateComponent = function (name) { - this._componentController.activate(name); + Viewer.prototype.setCenter = function (center) { + this._navigator.stateService.setCenter(center); }; /** - * Deactivate a component. + * Set the filter selecting nodes to use when calculating + * the spatial edges. * - * @param {string} name - Name of component which become inactive. + * @description The following filter types are supported: + * + * Comparison + * + * `["==", key, value]` equality: `node[key] = value` + * + * `["!=", key, value]` inequality: `node[key] ≠ value` + * + * `["<", key, value]` less than: `node[key] < value` + * + * `["<=", key, value]` less than or equal: `node[key] ≤ value` + * + * `[">", key, value]` greater than: `node[key] > value` + * + * `[">=", key, value]` greater than or equal: `node[key] ≥ value` + * + * Set membership + * + * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}` + * + * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}` + * + * Combining + * + * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn` + * + * A key must be a string that identifies a property name of a + * simple {@link Node} property. A value must be a string, number, or + * boolean. Strictly-typed comparisons are used. The values + * `f0, ..., fn` of the combining filter must be filter expressions. + * + * Clear the filter by setting it to null or empty array. + * + * @param {FilterExpression} filter - The filter expression. + * @returns {Promise} Promise that resolves after filter is applied. + * + * @example + * ``` + * viewer.setFilter(["==", "sequenceKey", ""]); + * ``` */ - Viewer.prototype.deactivateComponent = function (name) { - this._componentController.deactivate(name); + Viewer.prototype.setFilter = function (filter) { + var _this = this; + return when.promise(function (resolve, reject) { + _this._navigator.setFilter$(filter) + .subscribe(function () { + resolve(undefined); + }, function (error) { + reject(error); + }); + }); }; /** - * Get a component. + * Set the viewer's render mode. * - * @param {string} name - Name of component. - * @returns {Component} The requested component. + * @param {RenderMode} renderMode - Render mode. + * + * @example + * ``` + * viewer.setRenderMode(Mapillary.RenderMode.Letterbox); + * ``` */ - Viewer.prototype.getComponent = function (name) { - return this._componentController.get(name); + Viewer.prototype.setRenderMode = function (renderMode) { + this._container.renderService.renderMode$.next(renderMode); }; /** - * Activate the cover (deactivates all other components). + * Set the viewer's transition mode. + * + * @param {TransitionMode} transitionMode - Transition mode. + * + * @example + * ``` + * viewer.setTransitionMode(Mapillary.TransitionMode.Instantaneous); + * ``` */ - Viewer.prototype.activateCover = function () { - this._componentController.activateCover(); + Viewer.prototype.setTransitionMode = function (transitionMode) { + this._navigator.stateService.setTransitionMode(transitionMode); }; /** - * Deactivate the cover (activates all components marked as active). + * Set the image's current zoom level. + * + * @description Possible zoom level values are on the [0, 3] interval. + * Zero means zooming out to fit the image to the view whereas three + * shows the highest level of detail. + * + * @param {number} The image's current zoom level. + * + * @example + * ``` + * viewer.setZoom(2); + * ``` */ - Viewer.prototype.deactivateCover = function () { - this._componentController.deactivateCover(); + Viewer.prototype.setZoom = function (zoom) { + this._navigator.stateService.setZoom(zoom); }; /** - * Get the basic coordinates of the current photo that is - * at the center of the viewport. + * Unproject canvas pixel coordinates to an ILatLon representing geographical + * coordinates. * - * @description Basic coordinates are on the [0, 1] interval and - * has the origin point, [0, 0], at the top left corner and the - * maximum value, [1, 1], at the bottom right corner of the original - * photo. + * @description The pixel point may not always correspond to geographical + * coordinates. In the case of no correspondence the returned value will + * be `null`. * - * @returns {Promise} Promise to the basic coordinates - * of the current photo at the center for the viewport. + * @param {Array} pixelPoint - Pixel coordinates to unproject. + * @returns {Promise} Promise to the latLon corresponding to the pixel point. + * + * @example + * ``` + * viewer.unproject([100, 100]) + * .then((latLon) => { console.log(latLon); }); + * ``` */ - Viewer.prototype.getCenter = function () { + Viewer.prototype.unproject = function (pixelPoint) { var _this = this; return when.promise(function (resolve, reject) { - _this._navigator.stateService.getCenter() - .subscribe(function (center) { - resolve(center); + _this._observer.unproject$(pixelPoint) + .subscribe(function (latLon) { + resolve(latLon); }, function (error) { reject(error); }); }); }; /** - * Get the photo's current zoom level. + * Unproject canvas pixel coordinates to basic image coordinates for the + * current node. * - * @returns {Promise} Promise to the viewers's current - * zoom level. + * @description The pixel point may not always correspond to basic image + * coordinates. In the case of no correspondence the returned value will + * be `null`. + * + * @param {Array} pixelPoint - Pixel coordinates to unproject. + * @returns {Promise} Promise to the basic coordinates corresponding + * to the pixel point. + * + * @example + * ``` + * viewer.unprojectToBasic([100, 100]) + * .then((basicPoint) => { console.log(basicPoint); }); + * ``` */ - Viewer.prototype.getZoom = function () { + Viewer.prototype.unprojectToBasic = function (pixelPoint) { var _this = this; return when.promise(function (resolve, reject) { - _this._navigator.stateService.getZoom() - .subscribe(function (zoom) { - resolve(zoom); + _this._observer.unprojectBasic$(pixelPoint) + .subscribe(function (basicPoint) { + resolve(basicPoint); }, function (error) { reject(error); }); }); }; /** - * Set the basic coordinates of the current photo to be in the - * center of the viewport. + * Fired when the viewing direction of the camera changes. * - * @description Basic coordinates are on the [0, 1] interval and - * has the origin point, [0, 0], at the top left corner and the - * maximum value, [1, 1], at the bottom right corner of the original - * photo. + * @description Related to the computed compass angle + * ({@link Node.computedCa}) from SfM, not the original EXIF compass + * angle. * - * @param {number[]} The basic coordinates of the current - * photo to be at the center for the viewport. + * @event + * @type {number} bearing - Value indicating the current bearing + * measured in degrees clockwise with respect to north. */ - Viewer.prototype.setCenter = function (center) { - this._navigator.stateService.setCenter(center); - }; + Viewer.bearingchanged = "bearingchanged"; /** - * Set the photo's current zoom level. - * - * @description Possible zoom level values are on the [0, 3] interval. - * Zero means zooming out to fit the photo to the view whereas three - * shows the highest level of detail. - * - * @param {number} The photo's current zoom level. + * Fired when a pointing device (usually a mouse) is pressed and released at + * the same point in the viewer. + * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. */ - Viewer.prototype.setZoom = function (zoom) { - this._navigator.stateService.setZoom(zoom); - }; + Viewer.click = "click"; + /** + * Fired when the right button of the mouse is clicked within the viewer. + * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. + */ + Viewer.contextmenu = "contextmenu"; + /** + * Fired when a pointing device (usually a mouse) is clicked twice at + * the same point in the viewer. + * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. + */ + Viewer.dblclick = "dblclick"; /** * Fired when the viewer is loading more data. * @event - * @type {boolean} loading - Value indicating whether the viewer is loading. + * @type {boolean} loading - Boolean indicating whether the viewer is loading. */ Viewer.loadingchanged = "loadingchanged"; /** - * Fired when the viewer starts transitioning from one view to another, - * either by changing the node or by interaction such as pan and zoom. + * Fired when a pointing device (usually a mouse) is pressed within the viewer. * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. */ - Viewer.movestart = "movestart"; + Viewer.mousedown = "mousedown"; + /** + * Fired when a pointing device (usually a mouse) is moved within the viewer. + * @description Will not fire when the mouse is actively used, e.g. for drag pan. + * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. + */ + Viewer.mousemove = "mousemove"; + /** + * Fired when a pointing device (usually a mouse) leaves the viewer's canvas. + * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. + */ + Viewer.mouseout = "mouseout"; + /** + * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas. + * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. + */ + Viewer.mouseover = "mouseover"; /** - * Fired when the viewer finishes transitioning and is in a fixed + * Fired when a pointing device (usually a mouse) is released within the viewer. + * @event + * @type {IViewerMouseEvent} event - Viewer mouse event data. + */ + Viewer.mouseup = "mouseup"; + /** + * Fired when the viewer motion stops and it is in a fixed * position with a fixed point of view. * @event */ Viewer.moveend = "moveend"; + /** + * Fired when the motion from one view to another start, + * either by changing the position (e.g. when changing node) or + * when changing point of view (e.g. by interaction such as pan and zoom). + * @event + */ + Viewer.movestart = "movestart"; + /** + * Fired when the navigable state of the viewer changes. + * + * @description The navigable state indicates if the viewer supports + * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo` + * methods. The viewer will not be in a navigable state if the cover + * is activated and the viewer has been supplied a key. When the cover + * is deactivated or activated without being supplied a key it will + * be navigable. + * + * @event + * @type {boolean} navigable - Boolean indicating whether the viewer is navigable. + */ + Viewer.navigablechanged = "navigablechanged"; /** * Fired every time the viewer navigates to a new node. * @event @@ -33349,6 +48273,6 @@ var Viewer = (function (_super) { }(Utils_1.EventEmitter)); exports.Viewer = Viewer; -},{"../Utils":215,"../Viewer":216,"when":204}]},{},[212])(212) +},{"../Utils":300,"../Viewer":301,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/concat":39,"rxjs/add/observable/defer":40,"rxjs/add/observable/empty":41,"rxjs/add/observable/from":42,"rxjs/add/observable/fromEvent":43,"rxjs/add/observable/fromPromise":44,"rxjs/add/observable/merge":45,"rxjs/add/observable/of":46,"rxjs/add/observable/throw":47,"rxjs/add/observable/timer":48,"rxjs/add/observable/zip":49,"rxjs/add/operator/auditTime":50,"rxjs/add/operator/buffer":51,"rxjs/add/operator/bufferCount":52,"rxjs/add/operator/bufferWhen":53,"rxjs/add/operator/catch":54,"rxjs/add/operator/combineLatest":55,"rxjs/add/operator/concat":56,"rxjs/add/operator/count":57,"rxjs/add/operator/debounceTime":58,"rxjs/add/operator/delay":59,"rxjs/add/operator/distinct":60,"rxjs/add/operator/distinctUntilChanged":61,"rxjs/add/operator/do":62,"rxjs/add/operator/expand":63,"rxjs/add/operator/filter":64,"rxjs/add/operator/finally":65,"rxjs/add/operator/first":66,"rxjs/add/operator/last":67,"rxjs/add/operator/map":68,"rxjs/add/operator/merge":69,"rxjs/add/operator/mergeAll":70,"rxjs/add/operator/mergeMap":71,"rxjs/add/operator/pairwise":72,"rxjs/add/operator/pluck":73,"rxjs/add/operator/publish":74,"rxjs/add/operator/publishReplay":75,"rxjs/add/operator/reduce":76,"rxjs/add/operator/retry":77,"rxjs/add/operator/sample":78,"rxjs/add/operator/scan":79,"rxjs/add/operator/share":80,"rxjs/add/operator/skip":81,"rxjs/add/operator/skipUntil":82,"rxjs/add/operator/skipWhile":83,"rxjs/add/operator/startWith":84,"rxjs/add/operator/switchMap":85,"rxjs/add/operator/take":86,"rxjs/add/operator/takeUntil":87,"rxjs/add/operator/takeWhile":88,"rxjs/add/operator/timeout":89,"rxjs/add/operator/withLatestFrom":90,"rxjs/add/operator/zip":91,"when":287}]},{},[295])(295) }); //# sourceMappingURL=mapillary.js.map