1 (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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
4 var Queue = require('tinyqueue');
6 module.exports = polylabel;
7 module.exports.default = polylabel;
9 function polylabel(polygon, precision, debug) {
10 precision = precision || 1.0;
12 // find the bounding box of the outer ring
13 var minX, minY, maxX, maxY;
14 for (var i = 0; i < polygon[0].length; i++) {
15 var p = polygon[0][i];
16 if (!i || p[0] < minX) minX = p[0];
17 if (!i || p[1] < minY) minY = p[1];
18 if (!i || p[0] > maxX) maxX = p[0];
19 if (!i || p[1] > maxY) maxY = p[1];
22 var width = maxX - minX;
23 var height = maxY - minY;
24 var cellSize = Math.min(width, height);
27 // a priority queue of cells in order of their "potential" (max distance to polygon)
28 var cellQueue = new Queue(null, compareMax);
30 if (cellSize === 0) return [minX, minY];
32 // cover polygon with initial cells
33 for (var x = minX; x < maxX; x += cellSize) {
34 for (var y = minY; y < maxY; y += cellSize) {
35 cellQueue.push(new Cell(x + h, y + h, h, polygon));
39 // take centroid as the first best guess
40 var bestCell = getCentroidCell(polygon);
42 // special case for rectangular polygons
43 var bboxCell = new Cell(minX + width / 2, minY + height / 2, 0, polygon);
44 if (bboxCell.d > bestCell.d) bestCell = bboxCell;
46 var numProbes = cellQueue.length;
48 while (cellQueue.length) {
49 // pick the most promising cell from the queue
50 var cell = cellQueue.pop();
52 // update the best cell if we found a better one
53 if (cell.d > bestCell.d) {
55 if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes);
58 // do not drill down further if there's no chance of a better solution
59 if (cell.max - bestCell.d <= precision) continue;
61 // split the cell into four cells
63 cellQueue.push(new Cell(cell.x - h, cell.y - h, h, polygon));
64 cellQueue.push(new Cell(cell.x + h, cell.y - h, h, polygon));
65 cellQueue.push(new Cell(cell.x - h, cell.y + h, h, polygon));
66 cellQueue.push(new Cell(cell.x + h, cell.y + h, h, polygon));
71 console.log('num probes: ' + numProbes);
72 console.log('best distance: ' + bestCell.d);
75 return [bestCell.x, bestCell.y];
78 function compareMax(a, b) {
82 function Cell(x, y, h, polygon) {
83 this.x = x; // cell center x
84 this.y = y; // cell center y
85 this.h = h; // half the cell size
86 this.d = pointToPolygonDist(x, y, polygon); // distance from cell center to polygon
87 this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell
90 // signed distance from point to polygon outline (negative if point is outside)
91 function pointToPolygonDist(x, y, polygon) {
93 var minDistSq = Infinity;
95 for (var k = 0; k < polygon.length; k++) {
96 var ring = polygon[k];
98 for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
102 if ((a[1] > y !== b[1] > y) &&
103 (x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0])) inside = !inside;
105 minDistSq = Math.min(minDistSq, getSegDistSq(x, y, a, b));
109 return (inside ? 1 : -1) * Math.sqrt(minDistSq);
112 // get polygon centroid
113 function getCentroidCell(polygon) {
117 var points = polygon[0];
119 for (var i = 0, len = points.length, j = len - 1; i < len; j = i++) {
122 var f = a[0] * b[1] - b[0] * a[1];
123 x += (a[0] + b[0]) * f;
124 y += (a[1] + b[1]) * f;
127 if (area === 0) return new Cell(points[0][0], points[0][1], 0, polygon);
128 return new Cell(x / area, y / area, 0, polygon);
131 // get squared distance from a point to a segment
132 function getSegDistSq(px, py, a, b) {
139 if (dx !== 0 || dy !== 0) {
141 var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
156 return dx * dx + dy * dy;
159 },{"tinyqueue":232}],2:[function(require,module,exports){
161 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
163 * Redistribution and use in source and binary forms, with or without
164 * modification, are permitted provided that the following conditions
166 * 1. Redistributions of source code must retain the above copyright
167 * notice, this list of conditions and the following disclaimer.
168 * 2. Redistributions in binary form must reproduce the above copyright
169 * notice, this list of conditions and the following disclaimer in the
170 * documentation and/or other materials provided with the distribution.
172 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
173 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
174 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
175 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
176 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
177 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
178 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
179 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
180 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
181 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
182 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
185 * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
188 module.exports = UnitBezier;
190 function UnitBezier(p1x, p1y, p2x, p2y) {
191 // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
193 this.bx = 3.0 * (p2x - p1x) - this.cx;
194 this.ax = 1.0 - this.cx - this.bx;
197 this.by = 3.0 * (p2y - p1y) - this.cy;
198 this.ay = 1.0 - this.cy - this.by;
206 UnitBezier.prototype.sampleCurveX = function(t) {
207 // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
208 return ((this.ax * t + this.bx) * t + this.cx) * t;
211 UnitBezier.prototype.sampleCurveY = function(t) {
212 return ((this.ay * t + this.by) * t + this.cy) * t;
215 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
216 return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
219 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
220 if (typeof epsilon === 'undefined') epsilon = 1e-6;
222 var t0, t1, t2, x2, i;
224 // First try a few iterations of Newton's method -- normally very fast.
225 for (t2 = x, i = 0; i < 8; i++) {
227 x2 = this.sampleCurveX(t2) - x;
228 if (Math.abs(x2) < epsilon) return t2;
230 var d2 = this.sampleCurveDerivativeX(t2);
231 if (Math.abs(d2) < 1e-6) break;
236 // Fall back to the bisection method for reliability.
241 if (t2 < t0) return t0;
242 if (t2 > t1) return t1;
246 x2 = this.sampleCurveX(t2);
247 if (Math.abs(x2 - x) < epsilon) return t2;
255 t2 = (t1 - t0) * 0.5 + t0;
262 UnitBezier.prototype.solve = function(x, epsilon) {
263 return this.sampleCurveY(this.solveCurveX(x, epsilon));
266 },{}],3:[function(require,module,exports){
269 exports.byteLength = byteLength
270 exports.toByteArray = toByteArray
271 exports.fromByteArray = fromByteArray
275 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
277 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
278 for (var i = 0, len = code.length; i < len; ++i) {
280 revLookup[code.charCodeAt(i)] = i
283 revLookup['-'.charCodeAt(0)] = 62
284 revLookup['_'.charCodeAt(0)] = 63
286 function placeHoldersCount (b64) {
289 throw new Error('Invalid string. Length must be a multiple of 4')
292 // the number of equal signs (place holders)
293 // if there are two placeholders, than the two characters before it
294 // represent one byte
295 // if there is only one, then the three characters before it represent 2 bytes
296 // this is just a cheap hack to not do indexOf twice
297 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
300 function byteLength (b64) {
301 // base64 is 4/3 + up to two characters of the original data
302 return (b64.length * 3 / 4) - placeHoldersCount(b64)
305 function toByteArray (b64) {
306 var i, l, tmp, placeHolders, arr
308 placeHolders = placeHoldersCount(b64)
310 arr = new Arr((len * 3 / 4) - placeHolders)
312 // if there are placeholders, only get up to the last complete 4 chars
313 l = placeHolders > 0 ? len - 4 : len
317 for (i = 0; i < l; i += 4) {
318 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
319 arr[L++] = (tmp >> 16) & 0xFF
320 arr[L++] = (tmp >> 8) & 0xFF
321 arr[L++] = tmp & 0xFF
324 if (placeHolders === 2) {
325 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
326 arr[L++] = tmp & 0xFF
327 } else if (placeHolders === 1) {
328 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
329 arr[L++] = (tmp >> 8) & 0xFF
330 arr[L++] = tmp & 0xFF
336 function tripletToBase64 (num) {
337 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
340 function encodeChunk (uint8, start, end) {
343 for (var i = start; i < end; i += 3) {
344 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
345 output.push(tripletToBase64(tmp))
347 return output.join('')
350 function fromByteArray (uint8) {
352 var len = uint8.length
353 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
356 var maxChunkLength = 16383 // must be multiple of 3
358 // go through the array every three bytes, we'll deal with trailing stuff later
359 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
360 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
363 // pad the end with zeros, but make sure to not forget the extra bytes
364 if (extraBytes === 1) {
366 output += lookup[tmp >> 2]
367 output += lookup[(tmp << 4) & 0x3F]
369 } else if (extraBytes === 2) {
370 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
371 output += lookup[tmp >> 10]
372 output += lookup[(tmp >> 4) & 0x3F]
373 output += lookup[(tmp << 2) & 0x3F]
379 return parts.join('')
382 },{}],4:[function(require,module,exports){
384 },{}],5:[function(require,module,exports){
386 * Cross-Browser Split 1.1.1
387 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
388 * Available under the MIT License
389 * ECMAScript compliant, uniform cross-browser split method
393 * Splits a string into an array of strings using a regex or string separator. Matches of the
394 * separator are not included in the result array. However, if `separator` is a regex that contains
395 * capturing groups, backreferences are spliced into the result each time `separator` is matched.
396 * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
398 * @param {String} str String to split.
399 * @param {RegExp|String} separator Regex or string to use for separating the string.
400 * @param {Number} [limit] Maximum number of items to include in the result array.
401 * @returns {Array} Array of substrings.
405 * split('a b c d', ' ');
406 * // -> ['a', 'b', 'c', 'd']
409 * split('a b c d', ' ', 2);
412 * // Backreferences in result array
413 * split('..word1 word2..', /([a-z]+)(\d+)/i);
414 * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
416 module.exports = (function split(undef) {
418 var nativeSplit = String.prototype.split,
419 compliantExecNpcg = /()??/.exec("")[1] === undef,
420 // NPCG: nonparticipating capturing group
423 self = function(str, separator, limit) {
424 // If `separator` is not a regex, use `nativeSplit`
425 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
426 return nativeSplit.call(str, separator, limit);
429 flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
430 (separator.sticky ? "y" : ""),
433 // Make `global` and avoid `lastIndex` issues by working with a copy
434 separator = new RegExp(separator.source, flags + "g"),
435 separator2, match, lastIndex, lastLength;
436 str += ""; // Type-convert
437 if (!compliantExecNpcg) {
438 // Doesn't need flags gy, but they don't hurt
439 separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
441 /* Values for `limit`, per the spec:
442 * If undefined: 4294967295 // Math.pow(2, 32) - 1
443 * If 0, Infinity, or NaN: 0
444 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
445 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
446 * If other: Type-convert, then use the above rules
448 limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1
449 limit >>> 0; // ToUint32(limit)
450 while (match = separator.exec(str)) {
451 // `separator.lastIndex` is not reliable cross-browser
452 lastIndex = match.index + match[0].length;
453 if (lastIndex > lastLastIndex) {
454 output.push(str.slice(lastLastIndex, match.index));
455 // Fix browsers whose `exec` methods don't consistently return `undefined` for
456 // nonparticipating capturing groups
457 if (!compliantExecNpcg && match.length > 1) {
458 match[0].replace(separator2, function() {
459 for (var i = 1; i < arguments.length - 2; i++) {
460 if (arguments[i] === undef) {
466 if (match.length > 1 && match.index < str.length) {
467 Array.prototype.push.apply(output, match.slice(1));
469 lastLength = match[0].length;
470 lastLastIndex = lastIndex;
471 if (output.length >= limit) {
475 if (separator.lastIndex === match.index) {
476 separator.lastIndex++; // Avoid an infinite loop
479 if (lastLastIndex === str.length) {
480 if (lastLength || !separator.test("")) {
484 output.push(str.slice(lastLastIndex));
486 return output.length > limit ? output.slice(0, limit) : output;
492 },{}],6:[function(require,module,exports){
493 // shim for using process in browser
494 var process = module.exports = {};
496 // cached from whatever global is present so that test runners that stub it
497 // don't break things. But we need to wrap it in a try catch in case it is
498 // wrapped in strict mode code which doesn't define any globals. It's inside a
499 // function because try/catches deoptimize in certain engines.
501 var cachedSetTimeout;
502 var cachedClearTimeout;
504 function defaultSetTimout() {
505 throw new Error('setTimeout has not been defined');
507 function defaultClearTimeout () {
508 throw new Error('clearTimeout has not been defined');
512 if (typeof setTimeout === 'function') {
513 cachedSetTimeout = setTimeout;
515 cachedSetTimeout = defaultSetTimout;
518 cachedSetTimeout = defaultSetTimout;
521 if (typeof clearTimeout === 'function') {
522 cachedClearTimeout = clearTimeout;
524 cachedClearTimeout = defaultClearTimeout;
527 cachedClearTimeout = defaultClearTimeout;
530 function runTimeout(fun) {
531 if (cachedSetTimeout === setTimeout) {
532 //normal enviroments in sane situations
533 return setTimeout(fun, 0);
535 // if setTimeout wasn't available but was latter defined
536 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
537 cachedSetTimeout = setTimeout;
538 return setTimeout(fun, 0);
541 // when when somebody has screwed with setTimeout but no I.E. maddness
542 return cachedSetTimeout(fun, 0);
545 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
546 return cachedSetTimeout.call(null, fun, 0);
548 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
549 return cachedSetTimeout.call(this, fun, 0);
555 function runClearTimeout(marker) {
556 if (cachedClearTimeout === clearTimeout) {
557 //normal enviroments in sane situations
558 return clearTimeout(marker);
560 // if clearTimeout wasn't available but was latter defined
561 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
562 cachedClearTimeout = clearTimeout;
563 return clearTimeout(marker);
566 // when when somebody has screwed with setTimeout but no I.E. maddness
567 return cachedClearTimeout(marker);
570 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
571 return cachedClearTimeout.call(null, marker);
573 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
574 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
575 return cachedClearTimeout.call(this, marker);
583 var draining = false;
587 function cleanUpNextTick() {
588 if (!draining || !currentQueue) {
592 if (currentQueue.length) {
593 queue = currentQueue.concat(queue);
602 function drainQueue() {
606 var timeout = runTimeout(cleanUpNextTick);
609 var len = queue.length;
611 currentQueue = queue;
613 while (++queueIndex < len) {
615 currentQueue[queueIndex].run();
623 runClearTimeout(timeout);
626 process.nextTick = function (fun) {
627 var args = new Array(arguments.length - 1);
628 if (arguments.length > 1) {
629 for (var i = 1; i < arguments.length; i++) {
630 args[i - 1] = arguments[i];
633 queue.push(new Item(fun, args));
634 if (queue.length === 1 && !draining) {
635 runTimeout(drainQueue);
639 // v8 likes predictible objects
640 function Item(fun, array) {
644 Item.prototype.run = function () {
645 this.fun.apply(null, this.array);
647 process.title = 'browser';
648 process.browser = true;
651 process.version = ''; // empty string to avoid regexp issues
652 process.versions = {};
657 process.addListener = noop;
660 process.removeListener = noop;
661 process.removeAllListeners = noop;
663 process.prependListener = noop;
664 process.prependOnceListener = noop;
666 process.listeners = function (name) { return [] }
668 process.binding = function (name) {
669 throw new Error('process.binding is not supported');
672 process.cwd = function () { return '/' };
673 process.chdir = function (dir) {
674 throw new Error('process.chdir is not supported');
676 process.umask = function() { return 0; };
678 },{}],7:[function(require,module,exports){
680 * The buffer module from node.js, for the browser.
682 * @author Feross Aboukhadijeh <https://feross.org>
685 /* eslint-disable no-proto */
689 var base64 = require('base64-js')
690 var ieee754 = require('ieee754')
692 exports.Buffer = Buffer
693 exports.SlowBuffer = SlowBuffer
694 exports.INSPECT_MAX_BYTES = 50
696 var K_MAX_LENGTH = 0x7fffffff
697 exports.kMaxLength = K_MAX_LENGTH
700 * If `Buffer.TYPED_ARRAY_SUPPORT`:
701 * === true Use Uint8Array implementation (fastest)
702 * === false Print warning and recommend using `buffer` v4.x which has an Object
703 * implementation (most compatible, even IE6)
705 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
706 * Opera 11.6+, iOS 4.2+.
708 * We report that the browser does not support typed arrays if the are not subclassable
709 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
710 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
711 * for __proto__ and has a buggy typed array implementation.
713 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
715 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
716 typeof console.error === 'function') {
718 'This browser lacks typed array (Uint8Array) support which is required by ' +
719 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
723 function typedArraySupport () {
724 // Can typed array instances can be augmented?
726 var arr = new Uint8Array(1)
727 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
728 return arr.foo() === 42
734 function createBuffer (length) {
735 if (length > K_MAX_LENGTH) {
736 throw new RangeError('Invalid typed array length')
738 // Return an augmented `Uint8Array` instance
739 var buf = new Uint8Array(length)
740 buf.__proto__ = Buffer.prototype
745 * The Buffer constructor returns instances of `Uint8Array` that have their
746 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
747 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
748 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
749 * returns a single octet.
751 * The `Uint8Array` prototype remains unmodified.
754 function Buffer (arg, encodingOrOffset, length) {
756 if (typeof arg === 'number') {
757 if (typeof encodingOrOffset === 'string') {
759 'If encoding is specified then the first argument must be a string'
762 return allocUnsafe(arg)
764 return from(arg, encodingOrOffset, length)
767 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
768 if (typeof Symbol !== 'undefined' && Symbol.species &&
769 Buffer[Symbol.species] === Buffer) {
770 Object.defineProperty(Buffer, Symbol.species, {
778 Buffer.poolSize = 8192 // not used by this implementation
780 function from (value, encodingOrOffset, length) {
781 if (typeof value === 'number') {
782 throw new TypeError('"value" argument must not be a number')
785 if (isArrayBuffer(value)) {
786 return fromArrayBuffer(value, encodingOrOffset, length)
789 if (typeof value === 'string') {
790 return fromString(value, encodingOrOffset)
793 return fromObject(value)
797 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
798 * if value is a number.
799 * Buffer.from(str[, encoding])
801 * Buffer.from(buffer)
802 * Buffer.from(arrayBuffer[, byteOffset[, length]])
804 Buffer.from = function (value, encodingOrOffset, length) {
805 return from(value, encodingOrOffset, length)
808 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
809 // https://github.com/feross/buffer/pull/148
810 Buffer.prototype.__proto__ = Uint8Array.prototype
811 Buffer.__proto__ = Uint8Array
813 function assertSize (size) {
814 if (typeof size !== 'number') {
815 throw new TypeError('"size" argument must be a number')
816 } else if (size < 0) {
817 throw new RangeError('"size" argument must not be negative')
821 function alloc (size, fill, encoding) {
824 return createBuffer(size)
826 if (fill !== undefined) {
827 // Only pay attention to encoding if it's a string. This
828 // prevents accidentally sending in a number that would
829 // be interpretted as a start offset.
830 return typeof encoding === 'string'
831 ? createBuffer(size).fill(fill, encoding)
832 : createBuffer(size).fill(fill)
834 return createBuffer(size)
838 * Creates a new filled Buffer instance.
839 * alloc(size[, fill[, encoding]])
841 Buffer.alloc = function (size, fill, encoding) {
842 return alloc(size, fill, encoding)
845 function allocUnsafe (size) {
847 return createBuffer(size < 0 ? 0 : checked(size) | 0)
851 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
853 Buffer.allocUnsafe = function (size) {
854 return allocUnsafe(size)
857 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
859 Buffer.allocUnsafeSlow = function (size) {
860 return allocUnsafe(size)
863 function fromString (string, encoding) {
864 if (typeof encoding !== 'string' || encoding === '') {
868 if (!Buffer.isEncoding(encoding)) {
869 throw new TypeError('"encoding" must be a valid string encoding')
872 var length = byteLength(string, encoding) | 0
873 var buf = createBuffer(length)
875 var actual = buf.write(string, encoding)
877 if (actual !== length) {
878 // Writing a hex string, for example, that contains invalid characters will
879 // cause everything after the first invalid character to be ignored. (e.g.
880 // 'abxxcd' will be treated as 'ab')
881 buf = buf.slice(0, actual)
887 function fromArrayLike (array) {
888 var length = array.length < 0 ? 0 : checked(array.length) | 0
889 var buf = createBuffer(length)
890 for (var i = 0; i < length; i += 1) {
891 buf[i] = array[i] & 255
896 function fromArrayBuffer (array, byteOffset, length) {
897 if (byteOffset < 0 || array.byteLength < byteOffset) {
898 throw new RangeError('\'offset\' is out of bounds')
901 if (array.byteLength < byteOffset + (length || 0)) {
902 throw new RangeError('\'length\' is out of bounds')
906 if (byteOffset === undefined && length === undefined) {
907 buf = new Uint8Array(array)
908 } else if (length === undefined) {
909 buf = new Uint8Array(array, byteOffset)
911 buf = new Uint8Array(array, byteOffset, length)
914 // Return an augmented `Uint8Array` instance
915 buf.__proto__ = Buffer.prototype
919 function fromObject (obj) {
920 if (Buffer.isBuffer(obj)) {
921 var len = checked(obj.length) | 0
922 var buf = createBuffer(len)
924 if (buf.length === 0) {
928 obj.copy(buf, 0, 0, len)
933 if (isArrayBufferView(obj) || 'length' in obj) {
934 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
935 return createBuffer(0)
937 return fromArrayLike(obj)
940 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
941 return fromArrayLike(obj.data)
945 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
948 function checked (length) {
949 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
950 // length is NaN (which is otherwise coerced to zero.)
951 if (length >= K_MAX_LENGTH) {
952 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
953 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
958 function SlowBuffer (length) {
959 if (+length != length) { // eslint-disable-line eqeqeq
962 return Buffer.alloc(+length)
965 Buffer.isBuffer = function isBuffer (b) {
966 return b != null && b._isBuffer === true
969 Buffer.compare = function compare (a, b) {
970 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
971 throw new TypeError('Arguments must be Buffers')
974 if (a === b) return 0
979 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
992 Buffer.isEncoding = function isEncoding (encoding) {
993 switch (String(encoding).toLowerCase()) {
1011 Buffer.concat = function concat (list, length) {
1012 if (!Array.isArray(list)) {
1013 throw new TypeError('"list" argument must be an Array of Buffers')
1016 if (list.length === 0) {
1017 return Buffer.alloc(0)
1021 if (length === undefined) {
1023 for (i = 0; i < list.length; ++i) {
1024 length += list[i].length
1028 var buffer = Buffer.allocUnsafe(length)
1030 for (i = 0; i < list.length; ++i) {
1032 if (!Buffer.isBuffer(buf)) {
1033 throw new TypeError('"list" argument must be an Array of Buffers')
1035 buf.copy(buffer, pos)
1041 function byteLength (string, encoding) {
1042 if (Buffer.isBuffer(string)) {
1043 return string.length
1045 if (isArrayBufferView(string) || isArrayBuffer(string)) {
1046 return string.byteLength
1048 if (typeof string !== 'string') {
1049 string = '' + string
1052 var len = string.length
1053 if (len === 0) return 0
1055 // Use a for loop to avoid recursion
1056 var loweredCase = false
1066 return utf8ToBytes(string).length
1075 return base64ToBytes(string).length
1077 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1078 encoding = ('' + encoding).toLowerCase()
1083 Buffer.byteLength = byteLength
1085 function slowToString (encoding, start, end) {
1086 var loweredCase = false
1088 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1089 // property of a typed array.
1091 // This behaves neither like String nor Uint8Array in that we set start/end
1092 // to their upper/lower bounds if the value passed is out of range.
1093 // undefined is handled specially as per ECMA-262 6th Edition,
1094 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1095 if (start === undefined || start < 0) {
1098 // Return early if start > this.length. Done here to prevent potential uint32
1099 // coercion fail below.
1100 if (start > this.length) {
1104 if (end === undefined || end > this.length) {
1112 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1120 if (!encoding) encoding = 'utf8'
1125 return hexSlice(this, start, end)
1129 return utf8Slice(this, start, end)
1132 return asciiSlice(this, start, end)
1136 return latin1Slice(this, start, end)
1139 return base64Slice(this, start, end)
1145 return utf16leSlice(this, start, end)
1148 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1149 encoding = (encoding + '').toLowerCase()
1155 // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1156 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1157 // reliably in a browserify context because there could be multiple different
1158 // copies of the 'buffer' package in use. This method works even for Buffer
1159 // instances that were created from another copy of the `buffer` package.
1160 // See: https://github.com/feross/buffer/issues/154
1161 Buffer.prototype._isBuffer = true
1163 function swap (b, n, m) {
1169 Buffer.prototype.swap16 = function swap16 () {
1170 var len = this.length
1171 if (len % 2 !== 0) {
1172 throw new RangeError('Buffer size must be a multiple of 16-bits')
1174 for (var i = 0; i < len; i += 2) {
1175 swap(this, i, i + 1)
1180 Buffer.prototype.swap32 = function swap32 () {
1181 var len = this.length
1182 if (len % 4 !== 0) {
1183 throw new RangeError('Buffer size must be a multiple of 32-bits')
1185 for (var i = 0; i < len; i += 4) {
1186 swap(this, i, i + 3)
1187 swap(this, i + 1, i + 2)
1192 Buffer.prototype.swap64 = function swap64 () {
1193 var len = this.length
1194 if (len % 8 !== 0) {
1195 throw new RangeError('Buffer size must be a multiple of 64-bits')
1197 for (var i = 0; i < len; i += 8) {
1198 swap(this, i, i + 7)
1199 swap(this, i + 1, i + 6)
1200 swap(this, i + 2, i + 5)
1201 swap(this, i + 3, i + 4)
1206 Buffer.prototype.toString = function toString () {
1207 var length = this.length
1208 if (length === 0) return ''
1209 if (arguments.length === 0) return utf8Slice(this, 0, length)
1210 return slowToString.apply(this, arguments)
1213 Buffer.prototype.equals = function equals (b) {
1214 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1215 if (this === b) return true
1216 return Buffer.compare(this, b) === 0
1219 Buffer.prototype.inspect = function inspect () {
1221 var max = exports.INSPECT_MAX_BYTES
1222 if (this.length > 0) {
1223 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1224 if (this.length > max) str += ' ... '
1226 return '<Buffer ' + str + '>'
1229 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1230 if (!Buffer.isBuffer(target)) {
1231 throw new TypeError('Argument must be a Buffer')
1234 if (start === undefined) {
1237 if (end === undefined) {
1238 end = target ? target.length : 0
1240 if (thisStart === undefined) {
1243 if (thisEnd === undefined) {
1244 thisEnd = this.length
1247 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1248 throw new RangeError('out of range index')
1251 if (thisStart >= thisEnd && start >= end) {
1254 if (thisStart >= thisEnd) {
1266 if (this === target) return 0
1268 var x = thisEnd - thisStart
1270 var len = Math.min(x, y)
1272 var thisCopy = this.slice(thisStart, thisEnd)
1273 var targetCopy = target.slice(start, end)
1275 for (var i = 0; i < len; ++i) {
1276 if (thisCopy[i] !== targetCopy[i]) {
1283 if (x < y) return -1
1288 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1289 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1292 // - buffer - a Buffer to search
1293 // - val - a string, Buffer, or number
1294 // - byteOffset - an index into `buffer`; will be clamped to an int32
1295 // - encoding - an optional encoding, relevant is val is a string
1296 // - dir - true for indexOf, false for lastIndexOf
1297 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1298 // Empty buffer means no match
1299 if (buffer.length === 0) return -1
1301 // Normalize byteOffset
1302 if (typeof byteOffset === 'string') {
1303 encoding = byteOffset
1305 } else if (byteOffset > 0x7fffffff) {
1306 byteOffset = 0x7fffffff
1307 } else if (byteOffset < -0x80000000) {
1308 byteOffset = -0x80000000
1310 byteOffset = +byteOffset // Coerce to Number.
1311 if (numberIsNaN(byteOffset)) {
1312 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1313 byteOffset = dir ? 0 : (buffer.length - 1)
1316 // Normalize byteOffset: negative offsets start from the end of the buffer
1317 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1318 if (byteOffset >= buffer.length) {
1320 else byteOffset = buffer.length - 1
1321 } else if (byteOffset < 0) {
1322 if (dir) byteOffset = 0
1327 if (typeof val === 'string') {
1328 val = Buffer.from(val, encoding)
1331 // Finally, search either indexOf (if dir is true) or lastIndexOf
1332 if (Buffer.isBuffer(val)) {
1333 // Special case: looking for empty string/buffer always fails
1334 if (val.length === 0) {
1337 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1338 } else if (typeof val === 'number') {
1339 val = val & 0xFF // Search for a byte value [0-255]
1340 if (typeof Uint8Array.prototype.indexOf === 'function') {
1342 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1344 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1347 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1350 throw new TypeError('val must be string, number or Buffer')
1353 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1355 var arrLength = arr.length
1356 var valLength = val.length
1358 if (encoding !== undefined) {
1359 encoding = String(encoding).toLowerCase()
1360 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1361 encoding === 'utf16le' || encoding === 'utf-16le') {
1362 if (arr.length < 2 || val.length < 2) {
1372 function read (buf, i) {
1373 if (indexSize === 1) {
1376 return buf.readUInt16BE(i * indexSize)
1383 for (i = byteOffset; i < arrLength; i++) {
1384 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1385 if (foundIndex === -1) foundIndex = i
1386 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1388 if (foundIndex !== -1) i -= i - foundIndex
1393 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1394 for (i = byteOffset; i >= 0; i--) {
1396 for (var j = 0; j < valLength; j++) {
1397 if (read(arr, i + j) !== read(val, j)) {
1409 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1410 return this.indexOf(val, byteOffset, encoding) !== -1
1413 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1414 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1417 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1418 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1421 function hexWrite (buf, string, offset, length) {
1422 offset = Number(offset) || 0
1423 var remaining = buf.length - offset
1427 length = Number(length)
1428 if (length > remaining) {
1433 // must be an even number of digits
1434 var strLen = string.length
1435 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1437 if (length > strLen / 2) {
1440 for (var i = 0; i < length; ++i) {
1441 var parsed = parseInt(string.substr(i * 2, 2), 16)
1442 if (numberIsNaN(parsed)) return i
1443 buf[offset + i] = parsed
1448 function utf8Write (buf, string, offset, length) {
1449 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1452 function asciiWrite (buf, string, offset, length) {
1453 return blitBuffer(asciiToBytes(string), buf, offset, length)
1456 function latin1Write (buf, string, offset, length) {
1457 return asciiWrite(buf, string, offset, length)
1460 function base64Write (buf, string, offset, length) {
1461 return blitBuffer(base64ToBytes(string), buf, offset, length)
1464 function ucs2Write (buf, string, offset, length) {
1465 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1468 Buffer.prototype.write = function write (string, offset, length, encoding) {
1469 // Buffer#write(string)
1470 if (offset === undefined) {
1472 length = this.length
1474 // Buffer#write(string, encoding)
1475 } else if (length === undefined && typeof offset === 'string') {
1477 length = this.length
1479 // Buffer#write(string, offset[, length][, encoding])
1480 } else if (isFinite(offset)) {
1481 offset = offset >>> 0
1482 if (isFinite(length)) {
1483 length = length >>> 0
1484 if (encoding === undefined) encoding = 'utf8'
1491 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1495 var remaining = this.length - offset
1496 if (length === undefined || length > remaining) length = remaining
1498 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1499 throw new RangeError('Attempt to write outside buffer bounds')
1502 if (!encoding) encoding = 'utf8'
1504 var loweredCase = false
1508 return hexWrite(this, string, offset, length)
1512 return utf8Write(this, string, offset, length)
1515 return asciiWrite(this, string, offset, length)
1519 return latin1Write(this, string, offset, length)
1522 // Warning: maxLength not taken into account in base64Write
1523 return base64Write(this, string, offset, length)
1529 return ucs2Write(this, string, offset, length)
1532 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1533 encoding = ('' + encoding).toLowerCase()
1539 Buffer.prototype.toJSON = function toJSON () {
1542 data: Array.prototype.slice.call(this._arr || this, 0)
1546 function base64Slice (buf, start, end) {
1547 if (start === 0 && end === buf.length) {
1548 return base64.fromByteArray(buf)
1550 return base64.fromByteArray(buf.slice(start, end))
1554 function utf8Slice (buf, start, end) {
1555 end = Math.min(buf.length, end)
1560 var firstByte = buf[i]
1561 var codePoint = null
1562 var bytesPerSequence = (firstByte > 0xEF) ? 4
1563 : (firstByte > 0xDF) ? 3
1564 : (firstByte > 0xBF) ? 2
1567 if (i + bytesPerSequence <= end) {
1568 var secondByte, thirdByte, fourthByte, tempCodePoint
1570 switch (bytesPerSequence) {
1572 if (firstByte < 0x80) {
1573 codePoint = firstByte
1577 secondByte = buf[i + 1]
1578 if ((secondByte & 0xC0) === 0x80) {
1579 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1580 if (tempCodePoint > 0x7F) {
1581 codePoint = tempCodePoint
1586 secondByte = buf[i + 1]
1587 thirdByte = buf[i + 2]
1588 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1589 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1590 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1591 codePoint = tempCodePoint
1596 secondByte = buf[i + 1]
1597 thirdByte = buf[i + 2]
1598 fourthByte = buf[i + 3]
1599 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1600 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1601 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1602 codePoint = tempCodePoint
1608 if (codePoint === null) {
1609 // we did not generate a valid codePoint so insert a
1610 // replacement char (U+FFFD) and advance only 1 byte
1612 bytesPerSequence = 1
1613 } else if (codePoint > 0xFFFF) {
1614 // encode to utf16 (surrogate pair dance)
1615 codePoint -= 0x10000
1616 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1617 codePoint = 0xDC00 | codePoint & 0x3FF
1621 i += bytesPerSequence
1624 return decodeCodePointsArray(res)
1627 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1628 // the lowest limit is Chrome, with 0x10000 args.
1629 // We go 1 magnitude less, for safety
1630 var MAX_ARGUMENTS_LENGTH = 0x1000
1632 function decodeCodePointsArray (codePoints) {
1633 var len = codePoints.length
1634 if (len <= MAX_ARGUMENTS_LENGTH) {
1635 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1638 // Decode in chunks to avoid "call stack size exceeded".
1642 res += String.fromCharCode.apply(
1644 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1650 function asciiSlice (buf, start, end) {
1652 end = Math.min(buf.length, end)
1654 for (var i = start; i < end; ++i) {
1655 ret += String.fromCharCode(buf[i] & 0x7F)
1660 function latin1Slice (buf, start, end) {
1662 end = Math.min(buf.length, end)
1664 for (var i = start; i < end; ++i) {
1665 ret += String.fromCharCode(buf[i])
1670 function hexSlice (buf, start, end) {
1671 var len = buf.length
1673 if (!start || start < 0) start = 0
1674 if (!end || end < 0 || end > len) end = len
1677 for (var i = start; i < end; ++i) {
1678 out += toHex(buf[i])
1683 function utf16leSlice (buf, start, end) {
1684 var bytes = buf.slice(start, end)
1686 for (var i = 0; i < bytes.length; i += 2) {
1687 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1692 Buffer.prototype.slice = function slice (start, end) {
1693 var len = this.length
1695 end = end === undefined ? len : ~~end
1699 if (start < 0) start = 0
1700 } else if (start > len) {
1706 if (end < 0) end = 0
1707 } else if (end > len) {
1711 if (end < start) end = start
1713 var newBuf = this.subarray(start, end)
1714 // Return an augmented `Uint8Array` instance
1715 newBuf.__proto__ = Buffer.prototype
1720 * Need to make sure that buffer isn't trying to write out of bounds.
1722 function checkOffset (offset, ext, length) {
1723 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1724 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1727 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1728 offset = offset >>> 0
1729 byteLength = byteLength >>> 0
1730 if (!noAssert) checkOffset(offset, byteLength, this.length)
1732 var val = this[offset]
1735 while (++i < byteLength && (mul *= 0x100)) {
1736 val += this[offset + i] * mul
1742 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1743 offset = offset >>> 0
1744 byteLength = byteLength >>> 0
1746 checkOffset(offset, byteLength, this.length)
1749 var val = this[offset + --byteLength]
1751 while (byteLength > 0 && (mul *= 0x100)) {
1752 val += this[offset + --byteLength] * mul
1758 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1759 offset = offset >>> 0
1760 if (!noAssert) checkOffset(offset, 1, this.length)
1764 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1765 offset = offset >>> 0
1766 if (!noAssert) checkOffset(offset, 2, this.length)
1767 return this[offset] | (this[offset + 1] << 8)
1770 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1771 offset = offset >>> 0
1772 if (!noAssert) checkOffset(offset, 2, this.length)
1773 return (this[offset] << 8) | this[offset + 1]
1776 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1777 offset = offset >>> 0
1778 if (!noAssert) checkOffset(offset, 4, this.length)
1780 return ((this[offset]) |
1781 (this[offset + 1] << 8) |
1782 (this[offset + 2] << 16)) +
1783 (this[offset + 3] * 0x1000000)
1786 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1787 offset = offset >>> 0
1788 if (!noAssert) checkOffset(offset, 4, this.length)
1790 return (this[offset] * 0x1000000) +
1791 ((this[offset + 1] << 16) |
1792 (this[offset + 2] << 8) |
1796 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1797 offset = offset >>> 0
1798 byteLength = byteLength >>> 0
1799 if (!noAssert) checkOffset(offset, byteLength, this.length)
1801 var val = this[offset]
1804 while (++i < byteLength && (mul *= 0x100)) {
1805 val += this[offset + i] * mul
1809 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1814 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1815 offset = offset >>> 0
1816 byteLength = byteLength >>> 0
1817 if (!noAssert) checkOffset(offset, byteLength, this.length)
1821 var val = this[offset + --i]
1822 while (i > 0 && (mul *= 0x100)) {
1823 val += this[offset + --i] * mul
1827 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1832 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1833 offset = offset >>> 0
1834 if (!noAssert) checkOffset(offset, 1, this.length)
1835 if (!(this[offset] & 0x80)) return (this[offset])
1836 return ((0xff - this[offset] + 1) * -1)
1839 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1840 offset = offset >>> 0
1841 if (!noAssert) checkOffset(offset, 2, this.length)
1842 var val = this[offset] | (this[offset + 1] << 8)
1843 return (val & 0x8000) ? val | 0xFFFF0000 : val
1846 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1847 offset = offset >>> 0
1848 if (!noAssert) checkOffset(offset, 2, this.length)
1849 var val = this[offset + 1] | (this[offset] << 8)
1850 return (val & 0x8000) ? val | 0xFFFF0000 : val
1853 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1854 offset = offset >>> 0
1855 if (!noAssert) checkOffset(offset, 4, this.length)
1857 return (this[offset]) |
1858 (this[offset + 1] << 8) |
1859 (this[offset + 2] << 16) |
1860 (this[offset + 3] << 24)
1863 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1864 offset = offset >>> 0
1865 if (!noAssert) checkOffset(offset, 4, this.length)
1867 return (this[offset] << 24) |
1868 (this[offset + 1] << 16) |
1869 (this[offset + 2] << 8) |
1873 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1874 offset = offset >>> 0
1875 if (!noAssert) checkOffset(offset, 4, this.length)
1876 return ieee754.read(this, offset, true, 23, 4)
1879 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1880 offset = offset >>> 0
1881 if (!noAssert) checkOffset(offset, 4, this.length)
1882 return ieee754.read(this, offset, false, 23, 4)
1885 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1886 offset = offset >>> 0
1887 if (!noAssert) checkOffset(offset, 8, this.length)
1888 return ieee754.read(this, offset, true, 52, 8)
1891 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1892 offset = offset >>> 0
1893 if (!noAssert) checkOffset(offset, 8, this.length)
1894 return ieee754.read(this, offset, false, 52, 8)
1897 function checkInt (buf, value, offset, ext, max, min) {
1898 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1899 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1900 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1903 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1905 offset = offset >>> 0
1906 byteLength = byteLength >>> 0
1908 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1909 checkInt(this, value, offset, byteLength, maxBytes, 0)
1914 this[offset] = value & 0xFF
1915 while (++i < byteLength && (mul *= 0x100)) {
1916 this[offset + i] = (value / mul) & 0xFF
1919 return offset + byteLength
1922 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1924 offset = offset >>> 0
1925 byteLength = byteLength >>> 0
1927 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1928 checkInt(this, value, offset, byteLength, maxBytes, 0)
1931 var i = byteLength - 1
1933 this[offset + i] = value & 0xFF
1934 while (--i >= 0 && (mul *= 0x100)) {
1935 this[offset + i] = (value / mul) & 0xFF
1938 return offset + byteLength
1941 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1943 offset = offset >>> 0
1944 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1945 this[offset] = (value & 0xff)
1949 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1951 offset = offset >>> 0
1952 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1953 this[offset] = (value & 0xff)
1954 this[offset + 1] = (value >>> 8)
1958 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1960 offset = offset >>> 0
1961 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1962 this[offset] = (value >>> 8)
1963 this[offset + 1] = (value & 0xff)
1967 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1969 offset = offset >>> 0
1970 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1971 this[offset + 3] = (value >>> 24)
1972 this[offset + 2] = (value >>> 16)
1973 this[offset + 1] = (value >>> 8)
1974 this[offset] = (value & 0xff)
1978 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1980 offset = offset >>> 0
1981 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1982 this[offset] = (value >>> 24)
1983 this[offset + 1] = (value >>> 16)
1984 this[offset + 2] = (value >>> 8)
1985 this[offset + 3] = (value & 0xff)
1989 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1991 offset = offset >>> 0
1993 var limit = Math.pow(2, (8 * byteLength) - 1)
1995 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2001 this[offset] = value & 0xFF
2002 while (++i < byteLength && (mul *= 0x100)) {
2003 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2006 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2009 return offset + byteLength
2012 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2014 offset = offset >>> 0
2016 var limit = Math.pow(2, (8 * byteLength) - 1)
2018 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2021 var i = byteLength - 1
2024 this[offset + i] = value & 0xFF
2025 while (--i >= 0 && (mul *= 0x100)) {
2026 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2029 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2032 return offset + byteLength
2035 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2037 offset = offset >>> 0
2038 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2039 if (value < 0) value = 0xff + value + 1
2040 this[offset] = (value & 0xff)
2044 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2046 offset = offset >>> 0
2047 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2048 this[offset] = (value & 0xff)
2049 this[offset + 1] = (value >>> 8)
2053 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2055 offset = offset >>> 0
2056 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2057 this[offset] = (value >>> 8)
2058 this[offset + 1] = (value & 0xff)
2062 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2064 offset = offset >>> 0
2065 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2066 this[offset] = (value & 0xff)
2067 this[offset + 1] = (value >>> 8)
2068 this[offset + 2] = (value >>> 16)
2069 this[offset + 3] = (value >>> 24)
2073 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2075 offset = offset >>> 0
2076 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2077 if (value < 0) value = 0xffffffff + value + 1
2078 this[offset] = (value >>> 24)
2079 this[offset + 1] = (value >>> 16)
2080 this[offset + 2] = (value >>> 8)
2081 this[offset + 3] = (value & 0xff)
2085 function checkIEEE754 (buf, value, offset, ext, max, min) {
2086 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2087 if (offset < 0) throw new RangeError('Index out of range')
2090 function writeFloat (buf, value, offset, littleEndian, noAssert) {
2092 offset = offset >>> 0
2094 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2096 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2100 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2101 return writeFloat(this, value, offset, true, noAssert)
2104 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2105 return writeFloat(this, value, offset, false, noAssert)
2108 function writeDouble (buf, value, offset, littleEndian, noAssert) {
2110 offset = offset >>> 0
2112 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2114 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2118 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2119 return writeDouble(this, value, offset, true, noAssert)
2122 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2123 return writeDouble(this, value, offset, false, noAssert)
2126 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2127 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2128 if (!start) start = 0
2129 if (!end && end !== 0) end = this.length
2130 if (targetStart >= target.length) targetStart = target.length
2131 if (!targetStart) targetStart = 0
2132 if (end > 0 && end < start) end = start
2134 // Copy 0 bytes; we're done
2135 if (end === start) return 0
2136 if (target.length === 0 || this.length === 0) return 0
2138 // Fatal error conditions
2139 if (targetStart < 0) {
2140 throw new RangeError('targetStart out of bounds')
2142 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2143 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2146 if (end > this.length) end = this.length
2147 if (target.length - targetStart < end - start) {
2148 end = target.length - targetStart + start
2151 var len = end - start
2154 if (this === target && start < targetStart && targetStart < end) {
2155 // descending copy from end
2156 for (i = len - 1; i >= 0; --i) {
2157 target[i + targetStart] = this[i + start]
2159 } else if (len < 1000) {
2160 // ascending copy from start
2161 for (i = 0; i < len; ++i) {
2162 target[i + targetStart] = this[i + start]
2165 Uint8Array.prototype.set.call(
2167 this.subarray(start, start + len),
2176 // buffer.fill(number[, offset[, end]])
2177 // buffer.fill(buffer[, offset[, end]])
2178 // buffer.fill(string[, offset[, end]][, encoding])
2179 Buffer.prototype.fill = function fill (val, start, end, encoding) {
2180 // Handle string cases:
2181 if (typeof val === 'string') {
2182 if (typeof start === 'string') {
2186 } else if (typeof end === 'string') {
2190 if (val.length === 1) {
2191 var code = val.charCodeAt(0)
2196 if (encoding !== undefined && typeof encoding !== 'string') {
2197 throw new TypeError('encoding must be a string')
2199 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2200 throw new TypeError('Unknown encoding: ' + encoding)
2202 } else if (typeof val === 'number') {
2206 // Invalid ranges are not set to a default, so can range check early.
2207 if (start < 0 || this.length < start || this.length < end) {
2208 throw new RangeError('Out of range index')
2216 end = end === undefined ? this.length : end >>> 0
2221 if (typeof val === 'number') {
2222 for (i = start; i < end; ++i) {
2226 var bytes = Buffer.isBuffer(val)
2228 : new Buffer(val, encoding)
2229 var len = bytes.length
2230 for (i = 0; i < end - start; ++i) {
2231 this[i + start] = bytes[i % len]
2241 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2243 function base64clean (str) {
2244 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2245 str = str.trim().replace(INVALID_BASE64_RE, '')
2246 // Node converts strings with length < 2 to ''
2247 if (str.length < 2) return ''
2248 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2249 while (str.length % 4 !== 0) {
2255 function toHex (n) {
2256 if (n < 16) return '0' + n.toString(16)
2257 return n.toString(16)
2260 function utf8ToBytes (string, units) {
2261 units = units || Infinity
2263 var length = string.length
2264 var leadSurrogate = null
2267 for (var i = 0; i < length; ++i) {
2268 codePoint = string.charCodeAt(i)
2270 // is surrogate component
2271 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2272 // last char was a lead
2273 if (!leadSurrogate) {
2275 if (codePoint > 0xDBFF) {
2277 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2279 } else if (i + 1 === length) {
2281 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2286 leadSurrogate = codePoint
2292 if (codePoint < 0xDC00) {
2293 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2294 leadSurrogate = codePoint
2298 // valid surrogate pair
2299 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2300 } else if (leadSurrogate) {
2301 // valid bmp char, but last char was a lead
2302 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2305 leadSurrogate = null
2308 if (codePoint < 0x80) {
2309 if ((units -= 1) < 0) break
2310 bytes.push(codePoint)
2311 } else if (codePoint < 0x800) {
2312 if ((units -= 2) < 0) break
2314 codePoint >> 0x6 | 0xC0,
2315 codePoint & 0x3F | 0x80
2317 } else if (codePoint < 0x10000) {
2318 if ((units -= 3) < 0) break
2320 codePoint >> 0xC | 0xE0,
2321 codePoint >> 0x6 & 0x3F | 0x80,
2322 codePoint & 0x3F | 0x80
2324 } else if (codePoint < 0x110000) {
2325 if ((units -= 4) < 0) break
2327 codePoint >> 0x12 | 0xF0,
2328 codePoint >> 0xC & 0x3F | 0x80,
2329 codePoint >> 0x6 & 0x3F | 0x80,
2330 codePoint & 0x3F | 0x80
2333 throw new Error('Invalid code point')
2340 function asciiToBytes (str) {
2342 for (var i = 0; i < str.length; ++i) {
2343 // Node's code seems to be doing this and not & 0x7F..
2344 byteArray.push(str.charCodeAt(i) & 0xFF)
2349 function utf16leToBytes (str, units) {
2352 for (var i = 0; i < str.length; ++i) {
2353 if ((units -= 2) < 0) break
2355 c = str.charCodeAt(i)
2365 function base64ToBytes (str) {
2366 return base64.toByteArray(base64clean(str))
2369 function blitBuffer (src, dst, offset, length) {
2370 for (var i = 0; i < length; ++i) {
2371 if ((i + offset >= dst.length) || (i >= src.length)) break
2372 dst[i + offset] = src[i]
2377 // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
2378 // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
2379 function isArrayBuffer (obj) {
2380 return obj instanceof ArrayBuffer ||
2381 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
2382 typeof obj.byteLength === 'number')
2385 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2386 function isArrayBufferView (obj) {
2387 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2390 function numberIsNaN (obj) {
2391 return obj !== obj // eslint-disable-line no-self-compare
2394 },{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){
2397 module.exports = earcut;
2398 module.exports.default = earcut;
2400 function earcut(data, holeIndices, dim) {
2404 var hasHoles = holeIndices && holeIndices.length,
2405 outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2406 outerNode = linkedList(data, 0, outerLen, dim, true),
2409 if (!outerNode) return triangles;
2411 var minX, minY, maxX, maxY, x, y, invSize;
2413 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2415 // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2416 if (data.length > 80 * dim) {
2417 minX = maxX = data[0];
2418 minY = maxY = data[1];
2420 for (var i = dim; i < outerLen; i += dim) {
2423 if (x < minX) minX = x;
2424 if (y < minY) minY = y;
2425 if (x > maxX) maxX = x;
2426 if (y > maxY) maxY = y;
2429 // minX, minY and invSize are later used to transform coords into integers for z-order calculation
2430 invSize = Math.max(maxX - minX, maxY - minY);
2431 invSize = invSize !== 0 ? 1 / invSize : 0;
2434 earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
2439 // create a circular doubly linked list from polygon points in the specified winding order
2440 function linkedList(data, start, end, dim, clockwise) {
2443 if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2444 for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2446 for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2449 if (last && equals(last, last.next)) {
2457 // eliminate colinear or duplicate points
2458 function filterPoints(start, end) {
2459 if (!start) return start;
2460 if (!end) end = start;
2467 if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2470 if (p === p.next) break;
2476 } while (again || p !== end);
2481 // main ear slicing loop which triangulates a polygon (given as a linked list)
2482 function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
2485 // interlink polygon nodes in z-order
2486 if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
2491 // iterate through ears, slicing them one by one
2492 while (ear.prev !== ear.next) {
2496 if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
2497 // cut off the triangle
2498 triangles.push(prev.i / dim);
2499 triangles.push(ear.i / dim);
2500 triangles.push(next.i / dim);
2504 // skipping the next vertice leads to less sliver triangles
2513 // if we looped through the whole remaining polygon and can't find any more ears
2515 // try filtering points and slicing again
2517 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
2519 // if this didn't work, try curing all small self-intersections locally
2520 } else if (pass === 1) {
2521 ear = cureLocalIntersections(ear, triangles, dim);
2522 earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
2524 // as a last resort, try splitting the remaining polygon into two
2525 } else if (pass === 2) {
2526 splitEarcut(ear, triangles, dim, minX, minY, invSize);
2534 // check whether a polygon node forms a valid ear with adjacent nodes
2535 function isEar(ear) {
2540 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2542 // now make sure we don't have other points inside the potential ear
2543 var p = ear.next.next;
2545 while (p !== ear.prev) {
2546 if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2547 area(p.prev, p, p.next) >= 0) return false;
2554 function isEarHashed(ear, minX, minY, invSize) {
2559 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2561 // triangle bbox; min & max are calculated like this for speed
2562 var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2563 minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2564 maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2565 maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2567 // z-order range for the current triangle bbox;
2568 var minZ = zOrder(minTX, minTY, minX, minY, invSize),
2569 maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
2571 // first look for points inside the triangle in increasing z-order
2574 while (p && p.z <= maxZ) {
2575 if (p !== ear.prev && p !== ear.next &&
2576 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2577 area(p.prev, p, p.next) >= 0) return false;
2581 // then look for points in decreasing z-order
2584 while (p && p.z >= minZ) {
2585 if (p !== ear.prev && p !== ear.next &&
2586 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2587 area(p.prev, p, p.next) >= 0) return false;
2594 // go through all polygon nodes and cure small local self-intersections
2595 function cureLocalIntersections(start, triangles, dim) {
2601 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2603 triangles.push(a.i / dim);
2604 triangles.push(p.i / dim);
2605 triangles.push(b.i / dim);
2607 // remove two nodes involved
2614 } while (p !== start);
2619 // try splitting polygon into two and triangulate them independently
2620 function splitEarcut(start, triangles, dim, minX, minY, invSize) {
2621 // look for a valid diagonal that divides the polygon into two
2624 var b = a.next.next;
2625 while (b !== a.prev) {
2626 if (a.i !== b.i && isValidDiagonal(a, b)) {
2627 // split the polygon in two by the diagonal
2628 var c = splitPolygon(a, b);
2630 // filter colinear points around the cuts
2631 a = filterPoints(a, a.next);
2632 c = filterPoints(c, c.next);
2634 // run earcut on each half
2635 earcutLinked(a, triangles, dim, minX, minY, invSize);
2636 earcutLinked(c, triangles, dim, minX, minY, invSize);
2642 } while (a !== start);
2645 // link every hole into the outer loop, producing a single-ring polygon without holes
2646 function eliminateHoles(data, holeIndices, outerNode, dim) {
2648 i, len, start, end, list;
2650 for (i = 0, len = holeIndices.length; i < len; i++) {
2651 start = holeIndices[i] * dim;
2652 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2653 list = linkedList(data, start, end, dim, false);
2654 if (list === list.next) list.steiner = true;
2655 queue.push(getLeftmost(list));
2658 queue.sort(compareX);
2660 // process holes from left to right
2661 for (i = 0; i < queue.length; i++) {
2662 eliminateHole(queue[i], outerNode);
2663 outerNode = filterPoints(outerNode, outerNode.next);
2669 function compareX(a, b) {
2673 // find a bridge between vertices that connects hole with an outer ring and and link it
2674 function eliminateHole(hole, outerNode) {
2675 outerNode = findHoleBridge(hole, outerNode);
2677 var b = splitPolygon(outerNode, hole);
2678 filterPoints(b, b.next);
2682 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2683 function findHoleBridge(hole, outerNode) {
2690 // find a segment intersected by a ray from the hole's leftmost point to the left;
2691 // segment's endpoint with lesser x will be potential connection point
2693 if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
2694 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2695 if (x <= hx && x > qx) {
2698 if (hy === p.y) return p;
2699 if (hy === p.next.y) return p.next;
2701 m = p.x < p.next.x ? p : p.next;
2705 } while (p !== outerNode);
2707 if (!m) return null;
2709 if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2711 // look for points inside the triangle of hole point, segment intersection and endpoint;
2712 // if there are no points found, we have a valid connection;
2713 // otherwise choose the point of the minimum angle with the ray as connection point
2723 while (p !== stop) {
2724 if (hx >= p.x && p.x >= mx && hx !== p.x &&
2725 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2727 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2729 if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2741 // interlink polygon nodes in z-order
2742 function indexCurve(start, minX, minY, invSize) {
2745 if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
2749 } while (p !== start);
2751 p.prevZ.nextZ = null;
2757 // Simon Tatham's linked list merge sort algorithm
2758 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2759 function sortLinked(list) {
2760 var i, p, q, e, tail, numMerges, pSize, qSize,
2773 for (i = 0; i < inSize; i++) {
2780 while (pSize > 0 || (qSize > 0 && q)) {
2782 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
2792 if (tail) tail.nextZ = e;
2805 } while (numMerges > 1);
2810 // z-order of a point given coords and inverse of the longer side of data bbox
2811 function zOrder(x, y, minX, minY, invSize) {
2812 // coords are transformed into non-negative 15-bit integer range
2813 x = 32767 * (x - minX) * invSize;
2814 y = 32767 * (y - minY) * invSize;
2816 x = (x | (x << 8)) & 0x00FF00FF;
2817 x = (x | (x << 4)) & 0x0F0F0F0F;
2818 x = (x | (x << 2)) & 0x33333333;
2819 x = (x | (x << 1)) & 0x55555555;
2821 y = (y | (y << 8)) & 0x00FF00FF;
2822 y = (y | (y << 4)) & 0x0F0F0F0F;
2823 y = (y | (y << 2)) & 0x33333333;
2824 y = (y | (y << 1)) & 0x55555555;
2826 return x | (y << 1);
2829 // find the leftmost node of a polygon ring
2830 function getLeftmost(start) {
2834 if (p.x < leftmost.x) leftmost = p;
2836 } while (p !== start);
2841 // check if a point lies within a convex triangle
2842 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2843 return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2844 (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2845 (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2848 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2849 function isValidDiagonal(a, b) {
2850 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2851 locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2854 // signed area of a triangle
2855 function area(p, q, r) {
2856 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2859 // check if two points are equal
2860 function equals(p1, p2) {
2861 return p1.x === p2.x && p1.y === p2.y;
2864 // check if two segments intersect
2865 function intersects(p1, q1, p2, q2) {
2866 if ((equals(p1, q1) && equals(p2, q2)) ||
2867 (equals(p1, q2) && equals(p2, q1))) return true;
2868 return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2869 area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2872 // check if a polygon diagonal intersects any polygon segments
2873 function intersectsPolygon(a, b) {
2876 if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2877 intersects(p, p.next, a, b)) return true;
2884 // check if a polygon diagonal is locally inside the polygon
2885 function locallyInside(a, b) {
2886 return area(a.prev, a, a.next) < 0 ?
2887 area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2888 area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2891 // check if the middle point of a polygon diagonal is inside the polygon
2892 function middleInside(a, b) {
2895 px = (a.x + b.x) / 2,
2896 py = (a.y + b.y) / 2;
2898 if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
2899 (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2907 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2908 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2909 function splitPolygon(a, b) {
2910 var a2 = new Node(a.i, a.x, a.y),
2911 b2 = new Node(b.i, b.x, b.y),
2930 // create a node and optionally link it with previous one (in a circular doubly linked list)
2931 function insertNode(i, x, y, last) {
2932 var p = new Node(i, x, y);
2947 function removeNode(p) {
2948 p.next.prev = p.prev;
2949 p.prev.next = p.next;
2951 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2952 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2955 function Node(i, x, y) {
2956 // vertice index in coordinates array
2959 // vertex coordinates
2963 // previous and next vertice nodes in a polygon ring
2967 // z-order curve value
2970 // previous and next nodes in z-order
2974 // indicates whether this is a steiner point
2975 this.steiner = false;
2978 // return a percentage difference between the polygon area and its triangulation area;
2979 // used to verify correctness of triangulation
2980 earcut.deviation = function (data, holeIndices, dim, triangles) {
2981 var hasHoles = holeIndices && holeIndices.length;
2982 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2984 var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2986 for (var i = 0, len = holeIndices.length; i < len; i++) {
2987 var start = holeIndices[i] * dim;
2988 var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2989 polygonArea -= Math.abs(signedArea(data, start, end, dim));
2993 var trianglesArea = 0;
2994 for (i = 0; i < triangles.length; i += 3) {
2995 var a = triangles[i] * dim;
2996 var b = triangles[i + 1] * dim;
2997 var c = triangles[i + 2] * dim;
2998 trianglesArea += Math.abs(
2999 (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
3000 (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
3003 return polygonArea === 0 && trianglesArea === 0 ? 0 :
3004 Math.abs((trianglesArea - polygonArea) / polygonArea);
3007 function signedArea(data, start, end, dim) {
3009 for (var i = start, j = end - dim; i < end; i += dim) {
3010 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3016 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3017 earcut.flatten = function (data) {
3018 var dim = data[0][0].length,
3019 result = {vertices: [], holes: [], dimensions: dim},
3022 for (var i = 0; i < data.length; i++) {
3023 for (var j = 0; j < data[i].length; j++) {
3024 for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3027 holeIndex += data[i - 1].length;
3028 result.holes.push(holeIndex);
3034 },{}],9:[function(require,module,exports){
3037 var OneVersionConstraint = require('individual/one-version');
3039 var MY_VERSION = '7';
3040 OneVersionConstraint('ev-store', MY_VERSION);
3042 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3044 module.exports = EvStore;
3046 function EvStore(elem) {
3047 var hash = elem[hashKey];
3050 hash = elem[hashKey] = {};
3056 },{"individual/one-version":19}],10:[function(require,module,exports){
3058 var request = require('./request');
3059 var buildQueryObject = require('./buildQueryObject');
3060 var isArray = Array.isArray;
3062 function simpleExtend(obj, obj2) {
3064 for (prop in obj2) {
3065 obj[prop] = obj2[prop];
3070 function XMLHttpSource(jsongUrl, config) {
3071 this._jsongUrl = jsongUrl;
3072 if (typeof config === 'number') {
3078 this._config = simpleExtend({
3084 XMLHttpSource.prototype = {
3085 // because javascript
3086 constructor: XMLHttpSource,
3088 * buildQueryObject helper
3090 buildQueryObject: buildQueryObject,
3093 * @inheritDoc DataSource#get
3095 get: function httpSourceGet(pathSet) {
3097 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3101 var config = simpleExtend(queryObject, this._config);
3102 // pass context for onBeforeRequest callback
3104 return request(method, config, context);
3108 * @inheritDoc DataSource#set
3110 set: function httpSourceSet(jsongEnv) {
3111 var method = 'POST';
3112 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3113 jsonGraph: jsongEnv,
3116 var config = simpleExtend(queryObject, this._config);
3117 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3119 // pass context for onBeforeRequest callback
3121 return request(method, config, context);
3126 * @inheritDoc DataSource#call
3128 call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3129 // arguments defaults
3131 pathSuffix = pathSuffix || [];
3132 paths = paths || [];
3134 var method = 'POST';
3136 queryData.push('method=call');
3137 queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3138 queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3139 queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3140 queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3142 var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3143 var config = simpleExtend(queryObject, this._config);
3144 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3146 // pass context for onBeforeRequest callback
3148 return request(method, config, context);
3152 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3153 XMLHttpSource['default'] = XMLHttpSource;
3155 module.exports = XMLHttpSource;
3157 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3159 module.exports = function buildQueryObject(url, method, queryData) {
3162 var data = {url: url};
3163 var isQueryParamUrl = url.indexOf('?') !== -1;
3164 var startUrl = (isQueryParamUrl) ? '&' : '?';
3166 if (typeof queryData === 'string') {
3167 qData.push(queryData);
3170 keys = Object.keys(queryData);
3171 keys.forEach(function (k) {
3172 var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3173 qData.push(k + '=' + encodeURIComponent(value));
3177 if (method === 'GET') {
3178 data.url += startUrl + qData.join('&');
3180 data.data = qData.join('&');
3186 },{}],12:[function(require,module,exports){
3189 // Get CORS support even for older IE
3190 module.exports = function getCORSRequest() {
3191 var xhr = new global.XMLHttpRequest();
3192 if ('withCredentials' in xhr) {
3194 } else if (!!global.XDomainRequest) {
3195 return new XDomainRequest();
3197 throw new Error('CORS is not supported by your browser');
3201 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3203 },{}],13:[function(require,module,exports){
3206 module.exports = function getXMLHttpRequest() {
3210 if (global.XMLHttpRequest) {
3211 return new global.XMLHttpRequest();
3214 progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3215 for (i = 0; i < 3; i++) {
3217 progId = progIds[i];
3218 if (new global.ActiveXObject(progId)) {
3223 return new global.ActiveXObject(progId);
3225 throw new Error('XMLHttpRequest is not supported by your browser');
3230 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3232 },{}],14:[function(require,module,exports){
3234 var getXMLHttpRequest = require('./getXMLHttpRequest');
3235 var getCORSRequest = require('./getCORSRequest');
3236 var hasOwnProp = Object.prototype.hasOwnProperty;
3238 var noop = function() {};
3240 function Observable() {}
3242 Observable.create = function(subscribe) {
3243 var o = new Observable();
3245 o.subscribe = function(onNext, onError, onCompleted) {
3250 if (typeof onNext === 'function') {
3253 onError: (onError || noop),
3254 onCompleted: (onCompleted || noop)
3260 disposable = subscribe(observer);
3262 if (typeof disposable === 'function') {
3274 function request(method, options, context) {
3275 return Observable.create(function requestObserver(observer) {
3278 method: method || 'GET',
3282 responseType: 'json'
3291 for (prop in options) {
3292 if (hasOwnProp.call(options, prop)) {
3293 config[prop] = options[prop];
3297 // Add request with Headers
3298 if (!config.crossDomain && !config.headers['X-Requested-With']) {
3299 config.headers['X-Requested-With'] = 'XMLHttpRequest';
3302 // allow the user to mutate the config open
3303 if (context.onBeforeRequest != null) {
3304 context.onBeforeRequest(config);
3309 xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3311 observer.onError(err);
3314 // Takes the url and opens the connection
3316 xhr.open(config.method, config.url, config.async, config.user, config.password);
3318 xhr.open(config.method, config.url, config.async);
3321 // Sets timeout information
3322 xhr.timeout = config.timeout;
3324 // Anything but explicit false results in true.
3325 xhr.withCredentials = config.withCredentials !== false;
3327 // Fills the request headers
3328 headers = config.headers;
3329 for (header in headers) {
3330 if (hasOwnProp.call(headers, header)) {
3331 xhr.setRequestHeader(header, headers[header]);
3335 if (config.responseType) {
3337 xhr.responseType = config.responseType;
3339 // WebKit added support for the json responseType value on 09/03/2013
3340 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3341 // known to throw when setting the value "json" as the response type. Other older
3342 // browsers implementing the responseType
3344 // The json response type can be ignored if not supported, because JSON payloads are
3345 // parsed on the client-side regardless.
3346 if (config.responseType !== 'json') {
3352 xhr.onreadystatechange = function onreadystatechange(e) {
3354 if (xhr.readyState === 4) {
3357 onXhrLoad(observer, xhr, e);
3363 xhr.ontimeout = function ontimeout(e) {
3366 onXhrError(observer, xhr, 'timeout error', e);
3371 xhr.send(config.data);
3374 observer.onError(e);
3377 return function dispose() {
3378 // Doesn't work in IE9
3379 if (!isDone && xhr.readyState !== 4) {
3388 * General handling of ultimate failure (after appropriate retries)
3390 function _handleXhrError(observer, textStatus, errorThrown) {
3391 // IE9: cross-domain request may be considered errors
3393 errorThrown = new Error(textStatus);
3396 observer.onError(errorThrown);
3399 function onXhrLoad(observer, xhr, e) {
3404 // If there's no observer, the request has been (or is being) cancelled.
3405 if (xhr && observer) {
3406 responseType = xhr.responseType;
3407 // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3408 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3409 responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3411 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3412 var status = (xhr.status === 1223) ? 204 : xhr.status;
3414 if (status >= 200 && status <= 399) {
3416 if (responseType !== 'json') {
3417 responseData = JSON.parse(responseData || '');
3419 if (typeof responseData === 'string') {
3420 responseData = JSON.parse(responseData || '');
3423 _handleXhrError(observer, 'invalid json', e);
3425 observer.onNext(responseData);
3426 observer.onCompleted();
3429 } else if (status === 401 || status === 403 || status === 407) {
3431 return _handleXhrError(observer, responseData);
3433 } else if (status === 410) {
3435 return _handleXhrError(observer, responseData);
3437 } else if (status === 408 || status === 504) {
3439 return _handleXhrError(observer, responseData);
3443 return _handleXhrError(observer, responseData || ('Response code ' + status));
3449 function onXhrError(observer, xhr, status, e) {
3450 _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3453 module.exports = request;
3455 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3457 !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;s<r.length;s++)o(r[s]);return o}({1:[function(t,e,n){var r=t(32),o=t(130);r.atom=o.atom,r.ref=o.ref,r.error=o.error,r.pathValue=o.pathValue,r.HttpDataSource=t(125),e.exports=r},{125:125,130:130,32:32}],2:[function(t,e,n){function r(t){var e=t||{};this._root=e._root||new o(e),this._path=e.path||e._path||[],this._scheduler=e.scheduler||e._scheduler||new l,this._source=e.source||e._source,this._request=e.request||e._request||new s(this,this._scheduler),this._ID=N++,"number"==typeof e.maxSize?this._maxSize=e.maxSize:this._maxSize=e._maxSize||r.prototype._maxSize,"number"==typeof e.collectRatio?this._collectRatio=e.collectRatio:this._collectRatio=e._collectRatio||r.prototype._collectRatio,(e.boxed||e.hasOwnProperty("_boxed"))&&(this._boxed=e.boxed||e._boxed),(e.materialized||e.hasOwnProperty("_materialized"))&&(this._materialized=e.materialized||e._materialized),"boolean"==typeof e.treatErrorsAsValues?this._treatErrorsAsValues=e.treatErrorsAsValues:e.hasOwnProperty("_treatErrorsAsValues")&&(this._treatErrorsAsValues=e._treatErrorsAsValues),e.cache&&this.setCache(e.cache)}var o=t(4),i=t(3),s=t(55),u=t(64),a=t(65),c=t(61),p=t(63),h=t(73),f=t(75),l=t(74),d=t(81),v=t(84),y=t(49),b=t(134),m=t(88),g=t(100),w=t(96),x=t(102),_=t(98),S=t(99),E=t(77),C=t(76),A=t(130),N=0,k=t(116),O=function(){},P=t(14),j=t(19),D={pathValue:!0,pathSyntax:!0,json:!0,jsonGraph:!0},q=t(72);e.exports=r,r.ref=A.ref,r.atom=A.atom,r.error=A.error,r.pathValue=A.pathValue,r.prototype.constructor=r,r.prototype._materialized=!1,r.prototype._boxed=!1,r.prototype._progressive=!1,r.prototype._treatErrorsAsValues=!1,r.prototype._maxSize=Math.pow(2,53)-1,r.prototype._collectRatio=.75,r.prototype.get=t(71),r.prototype._getWithPaths=t(70),r.prototype.set=function(){var t=k(arguments,D,"set");return t!==!0?new u(function(e){e.onError(t)}):this._set.apply(this,arguments)},r.prototype.preload=function(){var t=k(arguments,q,"preload");if(t!==!0)return new u(function(e){e.onError(t)});var e=Array.prototype.slice.call(arguments),n=this;return new u(function(t){return n.get.apply(n,e).subscribe(function(){},function(e){t.onError(e)},function(){t.onCompleted()})})},r.prototype._set=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(w(r)?n-=1:r=void 0,t=new Array(n);++e<n;)t[e]=arguments[e];return a.create(this,t,r)},r.prototype.call=function(){var t,e=-1,n=arguments.length;for(t=new Array(n);++e<n;){var r=arguments[e];t[e]=r;var o=typeof r;if(e>1&&!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);++e<n;)if(t[e]=b.fromPath(arguments[e]),"object"!=typeof t[e])throw new Error("Invalid argument");p.create(this,t,r).subscribe(O,function(t){throw t})},r.prototype.deref=t(5),r.prototype.getValue=t(16),r.prototype.setValue=t(79),r.prototype._getValueSync=t(24),r.prototype._setValueSync=t(80),r.prototype._derefSync=t(6),r.prototype.setCache=function(t){var e=this._root.cache;if(t!==e){var n=this._root,r=this._path;this._path=[],this._root.cache={},"undefined"!=typeof e&&y(n,n.expired,m(e),0),S(t)?C(this,[t]):_(t)?E(this,[t]):g(t)&&E(this,[{json:t}]),this._path=r}else"undefined"==typeof e&&(this._root.cache={});return this},r.prototype.getCache=function(){var t=v(arguments);if(0===t.length)return P(this._root.cache);var e=[{}],n=this._path;return j.getWithPathsAsJSONGraph(this,t,e),this._path=n,e[0].jsonGraph},r.prototype.getVersion=function(t){var e=t&&b.fromPath(t)||[];if(Array.isArray(e)===!1)throw new Error("Model#getVersion must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._getVersion(this,e)},r.prototype._syncCheck=function(t){if(Boolean(this._source)&&this._root.syncRefCount<=0&&this._root.unsafeMode===!1)throw new Error("Model#"+t+" may only be called within the context of a request selector.");return!0},r.prototype._clone=function(t){var e=new r(this);for(var n in t){var o=t[n];"delete"===o?delete e[n]:e[n]=o}return e.setCache=void 0,e},r.prototype.batch=function(t){var e=t;"number"==typeof e?e=new f(Math.round(Math.abs(e))):e&&e.schedule||(e=new h);var n=this._clone();return n._request=new s(n,e),n},r.prototype.unbatch=function(){var t=this._clone();return t._request=new s(t,new l),t},r.prototype.treatErrorsAsValues=function(){return this._clone({_treatErrorsAsValues:!0})},r.prototype.asDataSource=function(){return new i(this)},r.prototype._materialize=function(){return this._clone({_materialized:!0})},r.prototype._dematerialize=function(){return this._clone({_materialized:"delete"})},r.prototype.boxValues=function(){return this._clone({_boxed:!0})},r.prototype.unboxValues=function(){return this._clone({_boxed:"delete"})},r.prototype.withoutDataSource=function(){return this._clone({_source:"delete"})},r.prototype.toJSON=function(){return{$type:"ref",value:this._path}},r.prototype.getPath=function(){return d(this._path)},r.prototype._getBoundValue=t(13),r.prototype._getVersion=t(18),r.prototype._getValueSync=t(17),r.prototype._getPathValuesAsPathMap=j.getWithPathsAsPathMap,r.prototype._getPathValuesAsJSONG=j.getWithPathsAsJSONGraph,r.prototype._setPathValuesAsJSON=t(78),r.prototype._setPathValuesAsJSONG=t(78),r.prototype._setPathValuesAsPathMap=t(78),r.prototype._setPathValuesAsValues=t(78),r.prototype._setPathMapsAsJSON=t(77),r.prototype._setPathMapsAsJSONG=t(77),r.prototype._setPathMapsAsPathMap=t(77),r.prototype._setPathMapsAsValues=t(77),r.prototype._setJSONGsAsJSON=t(76),r.prototype._setJSONGsAsJSONG=t(76),r.prototype._setJSONGsAsPathMap=t(76),r.prototype._setJSONGsAsValues=t(76),r.prototype._setCache=t(77),r.prototype._invalidatePathValuesAsJSON=t(48),r.prototype._invalidatePathMapsAsJSON=t(47)},{100:100,102:102,116:116,13:13,130:130,134:134,14:14,16:16,17:17,18:18,19:19,24:24,3:3,4:4,47:47,48:48,49:49,5:5,55:55,6:6,61:61,63:63,64:64,65:65,70:70,71:71,72:72,73:73,74:74,75:75,76:76,77:77,78:78,79:79,80:80,81:81,84:84,88:88,96:96,98:98,99:99}],3:[function(t,e,n){function r(t){this._model=t._materialize().treatErrorsAsValues()}r.prototype.get=function(t){return this._model.get.apply(this._model,t)._toJSONG()},r.prototype.set=function(t){return this._model.set(t)._toJSONG()},r.prototype.call=function(t,e,n,r){var o=[t,e,n].concat(r);return this._model.call.apply(this._model,o)._toJSONG()},e.exports=r},{}],4:[function(t,e,n){function r(t){var e=t||{};this.syncRefCount=0,this.expired=e.expired||[],this.unsafeMode=e.unsafeMode||!1,this.collectionScheduler=e.collectionScheduler||new s,this.cache={},o(e.comparator)&&(this.comparator=e.comparator),o(e.errorSelector)&&(this.errorSelector=e.errorSelector),o(e.onChange)&&(this.onChange=e.onChange)}var o=t(96),i=t(91),s=t(74);r.prototype.errorSelector=function(t,e){return e},r.prototype.comparator=function(t,e){return i(t,"value")&&i(e,"value")?t.value===e.value&&t.$type===e.$type&&t.$expires===e.$expires:t===e},e.exports=r},{74:74,91:91,96:96}],5:[function(t,e,n){function r(t,e){var n,r=!1;try{++t._root.syncRefCount,n=t._derefSync(e)}catch(i){n=i,r=!0}finally{--t._root.syncRefCount}return r?o.Observable["throw"](n):o.Observable["return"](n)}var o=t(159),i=t(134);e.exports=function(t){for(var e=this,n=-1,s=arguments.length-1,u=new Array(s),a=i.fromPath(t);++n<s;)u[n]=i.fromPath(arguments[n+1]);if(0===s)throw new Error("Model#deref requires at least one value path.");return o.Observable.defer(function(){return r(e,a)}).flatMap(function(t){if(Boolean(t)){if(s>0){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<y.length){if(g){v=d;break}v=d;continue}if(v=d,g&&u(d))break;if(b[c]||i(b,d),g===a){f?s(t,d,h,null,null,null,y,y.length,f):p(t,d),m=0,y=w,b=d,v=e;continue}break}v=void 0;break}if(m<y.length&&void 0!==v){for(var x=[],_=0;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;++r<o&&n&&!n.$type;)n=n[e[r]];return n}},{}],16:[function(t,e,n){var r=t(64),o=t(134);e.exports=function(t){for(var e=o.fromPath(t),n=0,i=e.length;++n<i;)if("object"==typeof e[n])return new r(function(t){t.onError(new Error("Paths must be simple paths"))});var s=this;return new r(function(t){return s.get(e).subscribe(function(n){for(var r=n.json,o=-1,i=e.length;r&&++o<i;)r=r[e[o]];t.onNext(r)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{134:134,64:64}],17:[function(t,e,n){var r=t(11),o=t(25),i=t(27),s=t(29).promote,u=t(120),a=t(118),c=t(119);e.exports=function(t,e,n){for(var p,h,f,l,d,v=t._root.cache,y=e.length,b=[],m=!1,g=!1,w=0,x=v,_=v,S=v,E=!0,C=!1;x&&y>w;){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=n<e.length?i(e,n):[],r(t,c,n,s,u,a,o)}},{30:30}],22:[function(t,e,n){var r=t(29),o=t(25),i=r.promote,s=t(120),u=t(118),a=t(119),c=t(37);e.exports=function(t,e,n,r,p,h,f,l,d,v){if(n){var y,b,m,g,w,x,_,S,E=!1;if(e&&i(t,e),e&&void 0!==e.value||(E=t._materialized),E)S={$type:u};else if(t._boxed)S=o(e);else if(e.$type===s||e.$type===a)S=d?o(e):e.value;else if(d){var C=e.value&&"object"==typeof e.value,A=!e[c];S=C||A?o(e):e.value}else S=e.value;if(p&&(p.hasValue=!0),d){for(w=n.jsonGraph,w||(w=n.jsonGraph={},n.paths=[]),y=0,b=l-1;b>y;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||e<r())}},{106:106}],28:[function(t,e,n){e.exports=function(t){return t._materialized&&!t._source}},{}],29:[function(t,e,n){function r(t,e){var n=t._root,r=n[i];if(r!==e){var o=e[a],s=e[u];s&&(s[a]=o),o&&(o[u]=s),e[a]=void 0,n[i]=e,e[u]=r,r[a]=e}}function o(t,e){var n=t._root,r=e[a],o=e[u];o&&(o[a]=r),r&&(r[u]=o),e[a]=void 0,e===n[i]&&(n[i]=void 0),e===n[s]&&(n[s]=void 0),e[c]=!0,n.expired.push(e)}var i=t(34),s=t(45),u=t(38),a=t(41),c=t(35);e.exports={promote:r,splice:o}},{34:34,35:35,38:38,41:41,45:45}],30:[function(t,e,n){function r(t,e){var n,r,o,i=[];for(r=0,o=e||0,n=t.length;n>o;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<p.length&&j&&j===u&&!i(k)){b&&o(t,k,p,E,f,l,null,w,P,b,g),a(t,k);var q=r(t,e,e,k,D,f,b);g=!0,k=q[0];var R=q[1];for(O=[],P=R.length,_=0;P>_;++_)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++<g);if(d[p]!==n){var A=n[l]||0;n[l]=A+1,n[u+A]=d,d[p]=n,d[f]=A}}return[n,b]}function i(t,e,n,r,i,u,a,c,p,h,f,l){for(var v=n.$type;v===d;){var y=o(i,t,n,c,p,h,f,l);if(n=y[0],_(n))return y;e=y[1],v=n&&n.$type}if(void 0!==v)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(40),c=t(39),p=t(33),h=t(46),f=t(42),l=t(44),d=t(120),v=t(13),y=t(50),b=t(88),m=t(91),g=t(100),w=t(95),x=t(96),_=t(102),S=t(86),E=t(92),C=t(115),A=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=E(),u=n._comparator,a=n._errorSelector,p=t._path,f=n.cache,l=p.length?v(t,p).value:f,d=l[c]||f,y=f[h],b=-1,m=e.length;++b<m;){var g=e[b];r(g.json,0,f,d,l,s,i,o,u,a)}var w=f[h],_=n.onChange;x(_)&&y!==w&&_()}},{100:100,102:102,109:109,115:115,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,88:88,91:91,92:92,95:95,96:96}],48:[function(t,e,n){function r(t,e,n,o,s,u,a,c){var p={},h=e<t.length-1,f=t[e],l=x(f,p);do{var d=i(n,o,s,l,h,!1,u,a,c),v=d[0],b=d[1];v&&(h?r(t,e+1,n,b,v,u,a,c):E(v,b,l,c)&&S(b,y(v),c,u)),l=x(f,p)}while(!p.done)}function o(t,e,n,r,o){if(b(e))return w(e,r,o),[void 0,t];v(o,e);var s=e,p=e.value,l=t;if(e=e[c],null!=e)l=e[a]||t;else{var d=0,y=p.length-1;l=e=t;do{var m=p[d],x=y>d,_=i(t,l,e,m,x,!0,n,r,o);if(e=_[0],g(e))return _;l=_[1]}while(d++<y);if(s[c]!==e){var S=e[f]||0;e[f]=S+1,e[u+S]=s,s[c]=e,s[h]=S}}return[e,l]}function i(t,e,n,r,i,u,a,c,p){for(var h=n.$type;h===l;){var f=o(t,n,a,c,p);if(n=f[0],g(n))return f;e=f[1],h=n.$type}if(void 0!==h)return[n,e];if(null==r){if(i)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(88),b=t(95),m=t(96),g=t(102),w=t(86),x=t(143).iterateKeySet,_=t(92),S=t(115),E=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=_(),u=t._path,c=n.cache,h=u.length?d(t,u).value:c,f=h[a]||c,l=c[p],v=-1,y=e.length;++v<y;){var b=e[v];r(b,0,c,f,h,s,i,o)}var g=c[p],w=n.onChange;m(w)&&l!==g&&w()}},{102:102,109:109,115:115,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,88:88,92:92,95:95,96:96}],49:[function(t,e,n){var r=t(36),o=t(39),i=t(34),s=t(45),u=t(38),a=t(41),c=t(108),p=t(115);e.exports=function(t,e,n,h,f,l){var d=n,v=f;"number"!=typeof v&&(v=.75);var y,b,m,g="number"==typeof l,w=h*v;for(b=e.pop();b;)m=b.$size||0,d-=m,g===!0?p(b,m,t,l):(y=b[o])&&c(b,y,b[r],t),b=e.pop();if(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.length<e.length){c=!0;var h=u._callbacks.length;u._callbacks[h]=n,u._requestedPaths[h]=a[0],u._optimizedPaths[h]=[],++u._count,p=r(u,h)}return[c,s,o,p]},_merge:function(t,e,n){var r=this,i=r.requestQueue.model,s=i._root,u=s.errorSelector,a=s.comparator,l=i._path;i._path=f;var d=o(t);if(e){var v=e;v instanceof Error&&(v={message:v.message}),v.$type||(v={$type:h,value:v});var y=d.map(function(t){return{path:t,value:v}});p(i,y,null,u,a)}else c(i,[{paths:d,jsonGraph:n.jsonGraph}],null,u,a);i._path=l}},e.exports=l},{119:119,57:57,59:59,60:60,76:76,78:78}],53:[function(t,e,n){function r(){this.length=0,this.pending=!1,this.pathmaps=[],s.call(this,this._subscribe)}var o=t(159),i=o.Observer,s=o.Observable,u=o.Disposable,a=o.SerialDisposable,c=o.CompositeDisposable,p=t(9),h=t(143),f=h.iterateKeySet;r.create=function(t,e,n){var r=new this;return r.queue=t,r.model=e,r.index=n,r},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.insertPath=function(t,e,n,r,o){var i=r||0,s=o||t.length-1,u=n||this.pathmaps[s+1]||(this.pathmaps[s+1]=Object.create(null));if(void 0===u||null===u)return!1;var a,c,p=t[i],h={};a=f(p,h);do{if(c=u[a],s>i){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<u;){var h=t[s];for(a=-1;++a<c;)if(o=e[a],o.insertPath(h,o.pending)){p[a]=o;continue t}r||(r=n.create(this,i,this.total++),e[a]=r,p[c++]=r),r.insertPath(h,!1)}var f=[],l=-1;for(a=-1;++a<c;)o=p[a],null!=o&&(f[++l]=o);return f},r.prototype.mergeJSONGraphs=function(t,e){var n=0,r=[],o=[],a=[],c=t.index,p=e.index;t.index=Math.max(c,p),r[-1]=t.jsonGraph||{},o[-1]=e.jsonGraph||{};t:for(;n>-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(){
3458 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&&++n<r;)e=e[d[n]];var o=m._derefSync(_).boxValues();return{model:o,localFn:e}}).flatMap(e).defaultIfEmpty(n(l._source)).mergeAll().flatMap(r),E=new a;return E.add(S.subscribe(function(e){var n=e.paths,r=e.invalidated,i=l.get.apply(l,n);"AsJSONG"===t.outputFormat&&(i=o(i._toJSONG()).doAction(function(t){t.invalidated=r})),E.add(i.subscribe(t))},function(e){t.onError(e)})),E}var s=t(159)&&t(158),u=s.Observable,a=s.CompositeDisposable,c=t(64),p=t(9),h=t(134),f=t(120);r.create=c.create,r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){return this},r.prototype.initialize=function(){return this},e.exports=r},{120:120,134:134,158:158,159:159,64:64,9:9}],62:[function(t,e,n){function r(t){i.call(this,t)}var o=t(159),i=o.Observable,s=t(64),u=t(134),a=t(88),c=t(49),p=t(81),h=t(46),f=Array.isArray,l=t(101),d=t(98),v=t(99);r.create=s.create,r.prototype=Object.create(i.prototype),r.prototype.constructor=r,r.prototype.subscribeCount=0,r.prototype.subscribeLimit=10,r.prototype.initialize=function(){for(var t,e,n=this.model,r=this.outputFormat||"AsPathMap",o=this.isProgressive,i=[{}],s=[],a=this.args,c=-1,h=a.length;++c<h;){var y,b=a[c];f(b)||"string"==typeof b?(b=u.fromPath(b),y="PathValues"):l(b)?(b.path=u.fromPath(b.path),y="PathValues"):v(b)?y="JSONGs":d(b)&&(y="PathMaps"),e!==y&&(e=y,t={inputType:y,arguments:[]},s.push(t),t.values=i),t.arguments.push(b)}return this.boundPath=p(n._path),this.groups=s,this.outputFormat=r,this.isProgressive=o,this.isCompleted=!1,this.isMaster=null==n._source,this.values=i,this},r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){var e=this["finally"](function(){var e=t._root,n=e.cache;e.collectionScheduler.schedule(function(){c(e,e.expired,a(n),t._maxSize,t._collectRatio,n[h])})});return new this.constructor(function(t){return e.subscribe(t)})},e.exports=r},{101:101,134:134,159:159,46:46,49:49,64:64,81:81,88:88,98:98,99:99}],63:[function(t,e,n){function r(t){u.call(this,t||o)}function o(t){for(var e=this.model,n=this.method,r=this.groups,o=-1,i=r.length;++o<i;){var u=r[o],a=u.inputType,c=u.arguments;if(c.length>0){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;++d<y;){var b=l[d],m=b.inputType,g=b.arguments;if(g.length>0){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={},_=e<t.length-1,S=t[e],E=m(S,x),C=d.index;;){f.depth=e;var A=i(n,o,s,u,a,c,E,_,!1,f,d,v,y,b,g,w);f[e]=E,f.index=e,d[d.index++]=E;var N=A[0],k=A[1];if(N&&(_?r(t,e+1,n,k,N,u,A[3],A[2],p,h,f,d,v,y,b,g,w):(l(b,N),p.push(f.slice(0,f.index+1)),h.push(d.slice(0,d.index)))),E=m(S,x),x.done)break;d.index=C}}function o(t,e,n,r,o,s,c,f,v,m,g){var w=e.value;if(s.splice(0,s.length),s.push.apply(s,w),d(e))return s.index=w.length,b(e,f,v),[void 0,t,r,n];l(v,e);var x=0,_=e,S=w.length-1,E=e=t,C=r=n;do{var A=w[x],N=S>x,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++<S);if(s.index=x,_[a]!==e){var O=e[h]||0;e[h]=O+1,e[u+O]=_,_[a]=e,_[p]=O}return[e,E,r,C]}function i(t,e,n,r,i,u,a,c,p,h,l,d,v,b,m,g){for(var x=n.$type;x===f;){var _=o(t,n,r,u,h,l,d,v,b,m,g);if(n=_[0],y(n))return _;e=_[1],u=_[2],i=_[3],x=n.$type}if(void 0!==x)return[n,e,u,i];if(null==a){if(c)throw new Error("`null` is not allowed in branch key positions.");n&&(a=n[s])}else e=n,i=u,n=e[a],u=i&&i[a];return n=w(e,n,u,a,h,l,d,v,b,m,g),[n,e,u,i]}var s=t(36),u=t(43),a=t(33),c=t(46),p=t(42),h=t(44),f=t(120),l=t(50),d=t(94),v=t(96),y=t(102),b=t(86),m=t(143).iterateKeySet,g=t(92),w=t(103);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,p=g(),h=s.cache,f=h[c],l=[],d=[],y=[],b=[],m=-1,w=e.length;++m<w;)for(var x=e[m],_=x.paths,S=x.jsonGraph,E=-1,C=_.length;++E<C;){var A=_[E];d.index=0,r(A,0,h,h,h,S,S,S,y,b,l,d,p,a,u,i,o)}var N=h[c],k=s.onChange;return v(k)&&f!==N&&k(),[y,b]}},{102:102,103:103,120:120,143:143,33:33,36:36,42:42,43:43,44:44,46:46,50:50,86:86,92:92,94:94,96:96}],77:[function(t,e,n){function r(t,e,n,o,u,a,c,p,h,f,l,d,v,y){var b=s(t);if(b&&b.length)for(var g=0,x=b.length,_=h.index;;){var S=b[g],E=t[S],C=w(E)&&!E.$type;p.depth=e;var A=i(n,o,u,S,E,C,!1,p,h,f,l,d,v,y);p[e]=S,p.index=e,h[h.index++]=S;var N=A[0],k=A[1];if(N&&(C?r(E,e+1,n,k,N,a,c,p,h,f,l,d,v,y):(m(d,N),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),++g>=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;++S<E;){var A=e[S],N=h.slice(0);N.index=x,r(A.json,0,l,v,d,g,w,m,N,c,a,u,i,o)}var k=l[f],O=s.onChange;return _(O)&&b!==k&&O(),[g,w]}},{100:100,102:102,104:104,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,91:91,92:92,95:95,96:96}],78:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,l,d,y,b){for(var m={},g=n<e.length-1,x=e[n],_=w(x,m),S=h.index;;){p.depth=n;var E=i(o,s,u,_,t,g,!1,p,h,f,l,d,y,b);p[n]=_,p.index=n,h[h.index++]=_;var C=E[0],A=E[1];if(C&&(g?r(t,e,n+1,o,A,C,a,c,p,h,f,l,d,y,b):(v(d,C),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),_=w(x,m),m.done)break;h.index=S}}function o(t,e,n,r,o,s,p,l,d,b){var w=n.value;if(o.splice(0,o.length),o.push.apply(o,w),y(n))return o.index=w.length,g(n,p,l),[void 0,e];v(l,n);var x=n,_=e;if(n=n[c],null!=n)_=n[a]||e,o.index=w.length;else{var S=0,E=w.length-1;_=n=e;do{var C=w[S],A=E>S,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++<E);if(o.index=S,x[c]!==n){var k=n[f]||0;n[f]=k+1,n[u+k]=x,x[c]=n,x[h]=k}}return[n,_]}function i(t,e,n,r,i,u,a,c,p,h,f,d,v,y){for(var b=n.$type;b===l;){var g=o(i,t,n,c,p,h,f,d,v,y);if(n=g[0],m(n))return g;e=g[1],b=n.$type}if(void 0!==b)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return n=_(e,n,r,i,u,a,c,p,h,f,d,v,y),[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(95),b=t(96),m=t(102),g=t(86),w=t(143).iterateKeySet,x=t(92),_=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,c=s.expired,h=x(),f=t._path,l=s.cache,v=f.length?d(t,f).value:l,y=v[a]||l,m=l[p],g=[],w=[],_=[],S=f.length,E=-1,C=e.length;++E<C;){var A=e[E],N=A.path,k=A.value,O=f.slice(0);O.index=S,r(k,N,0,l,y,v,w,_,g,O,h,c,u,i,o)}var P=l[p],j=s.onChange;return b(j)&&m!==P&&j(),[w,_]}},{102:102,104:104,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,92:92,95:95,96:96}],79:[function(t,e,n){var r=t(130),o=t(64),i=t(101);e.exports=function(t,e){for(var n=i(t)?t:r.pathValue(t,e),s=0,u=n.path,a=u.length;++s<a;)if("object"==typeof u[s])return new o(function(t){t.onError(new Error("Paths must be simple paths"))});var c=this;return new o(function(t){return c._set(n).subscribe(function(e){for(var n=e.json,r=-1,o=u.length;n&&++r<o;)n=n[u[r]];t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{101:101,130:130,64:64}],80:[function(t,e,n){var r=t(134),o=t(101),i=t(78);e.exports=function(t,e,n,s){var u=r.fromPath(t),a=e,c=n,p=s;if(o(u)?(p=c,c=a,a=u):a={path:u,value:a},o(a)===!1)throw new Error("Model#setValueSync must be called with an Array path.");return"function"!=typeof c&&(c=this._root._errorSelector),"function"!=typeof p&&(p=this._root._comparator),this._syncCheck("setValueSync")?(i(this,[a]),this._getValueSync(this,a.path).value):void 0}},{101:101,134:134,78:78}],81:[function(t,e,n){e.exports=function(t){if(!t)return t;for(var e=-1,n=t.length,r=[];++e<n;)r[e]=t[e];return r}},{}],82:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=-1,o=t.length,i=[];++r<o;)for(var s=e(t[r],r,t),u=-1,a=s.length;++u<a;)i[++n]=s[u];return i}},{}],83:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=t.length,o=new Array(r);++n<r;)o[n]=e(t[n],n,t);return o}},{}],84:[function(t,e,n){e.exports=function(t,e,n){var r=e||0,o=-1,i=t.length-r;0>i&&(i=0),n>0&&i>n&&(i=n);for(var s=new Array(i);++o<i;)s[o]=t[o+r];return s}},{}],85:[function(t,e,n){var r=t(40),o=t(91),i=Array.isArray,s=t(100);e.exports=function(t){var e=t;if(s(e)){e=i(t)?[]:{};var n=t;for(var u in n)u[0]!==r&&o(n,u)&&(e[u]=n[u])}return e}},{100:100,40:40,91:91}],86:[function(t,e,n){var r=t(51),o=t(35);e.exports=function(t,e,n){return t[o]||(t[o]=!0,e.push(t),r(n,t)),t}},{35:35,51:51}],87:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$expires||void 0}},{100:100}],88:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$size||0}},{100:100}],89:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$timestamp||void 0}},{100:100}],90:[function(t,e,n){var r=t(100);e.exports=function(t,e){var n=r(t)&&t.$type||void 0;return e&&n?"branch":n}},{100:100}],91:[function(t,e,n){var r=t(100),o=Object.prototype.hasOwnProperty;e.exports=function(t,e){return r(t)&&o.call(t,e)}},{100:100}],92:[function(t,e,n){var r=1;e.exports=function(){return r++}},{}],93:[function(t,e,n){var r=t(36),o=t(39),i=t(46);e.exports=function(t,e,n,s){return t[r]=n,t[o]=e,t[i]=s,e[n]=t,t}},{36:36,39:39,46:46}],94:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&e!==o&&e<r()}},{106:106,121:121,122:122}],95:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&(e===o||e<r())}},{106:106,121:121,122:122}],96:[function(t,e,n){var r="function";e.exports=function(t){return Boolean(t)&&typeof t===r}},{}],97:[function(t,e,n){var r=t(40);e.exports=function(t){return"$size"===t||t&&t.charAt(0)===r}},{40:40}],98:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&"json"in t}},{100:100}],99:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&r(t.paths)&&(o(t.jsonGraph)||o(t.jsong)||o(t.json)||o(t.values)||o(t.value))}},{100:100}],100:[function(t,e,n){var r="object";e.exports=function(t){return null!==t&&typeof t===r}},{}],101:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&(r(t.path)||"string"==typeof t.path)}},{100:100}],102:[function(t,e,n){var r="object";e.exports=function(t){return null==t||typeof t!==r}},{}],103:[function(t,e,n){var r=t(36),o=t(39),i=t(120),s=t(119),u=t(88),a=t(89),c=t(100),p=t(95),h=t(96),f=t(50),l=t(117),d=t(93),v=t(86),y=t(110),b=t(115),m=t(107);e.exports=function(t,e,n,g,w,x,_,S,E,C,A){var N,k,O,P,j,D,q;if(e===n){if(null===n)return e=l(n,void 0,n),t=b(t,-e.$size,E,_),e=d(e,t,g),f(E,e),e;if(void 0===n)return n;if(P=c(e),P&&(k=e.$type,null==k))return null==e[o]&&(e[r]=g,e[o]=t),e}else P=c(e),P&&(k=e.$type);if(k!==i){if(j=c(n),j&&(O=n.$type),P&&!k&&(null==n||j&&!O))return e}else{if(null==n)return p(e)?void v(e,S,E):e;if(j=c(n),j&&(O=n.$type,O===i))if(e===n){if(null!=e[o])return e}else if(D=e.$timestamp,q=n.$timestamp,!p(e)&&!p(n)&&D>q)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)<a(e)==!1,(k||O)&&h(C)&&(R=!C(e,n,x.slice(0,x.index)))),R&&(n=l(n,O,O?n.value:n),N=u(e)-u(n),e=y(e,n,t,g,E),t=b(t,N,E,_),e=d(e,t,g,_))}p(e)?v(e,S,E):f(E,e)}else null==e&&(e=d(n,t,g));return e}},{100:100,107:107,110:110,115:115,117:117,119:119,120:120,36:36,39:39,50:50,86:86,88:88,89:89,93:93,95:95,96:96}],104:[function(t,e,n){var r=t(120),o=t(119),i=t(90),s=t(88),u=t(89),a=t(95),c=t(102),p=t(96),h=t(117),f=t(86),l=t(93),d=t(110),v=t(115),y=t(114),b=t(107);e.exports=function(t,e,n,m,g,w,x,_,S,E,C,A,N){var k=i(e,w);if(g||w)k&&a(e)&&(k="expired",f(e,E,C)),(k&&k!==r||c(e))&&(e=d(e,{},t,n,C),e=l(e,t,n,S),e=y(e,S));else{var O=m,P=i(O),j=u(O)<u(e)==!1;if((k||P)&&p(A)&&(j=!A(e,O,_.slice(0,_.index))),j){P===o&&p(N)&&(O=N(b(x,n),O)),O=h(O,P,P?O.value:O);var D=s(e)-s(O);e=d(e,O,t,n,C),t=v(t,D,C,S),e=l(e,t,n,S)}}return e}},{102:102,107:107,110:110,114:114,115:115,117:117,119:119,120:120,86:86,88:88,89:89,90:90,93:93,95:95,96:96}],105:[function(t,e,n){e.exports=function(){}},{}],106:[function(t,e,n){e.exports=Date.now},{}],107:[function(t,e,n){e.exports=function(t,e){var n=t.slice(0,t.depth);return n[n.length]=e,n}},{}],108:[function(t,e,n){var r=t(120),o=t(39),i=t(51),s=t(100),u=t(112),a=t(113);e.exports=function(t,e,n,c){if(s(t)){var p=t.$type;return Boolean(p)&&(p===r&&a(t),i(c,t)),u(t),e[n]=t[o]=void 0,!0}return!1}},{100:100,112:112,113:113,120:120,39:39,51:51}],109:[function(t,e,n){var r=t(91),o=t(40),i=t(108);e.exports=function s(t,e,n,u){if(i(t,e,n,u)){if(null==t.$type)for(var a in t)a[0]!==o&&"$"!==a[0]&&r(t,a)&&s(t[a],t,a,u);return!0}return!1}},{108:108,40:40,91:91}],110:[function(t,e,n){var r=t(100),o=t(111),i=t(109);e.exports=function(t,e,n,s,u){return t===e?t:(r(t)&&(o(t,e),i(t,n,s,u)),n[s]=e,e)}},{100:100,109:109,111:111}],111:[function(t,e,n){var r=t(43),o=t(33),i=t(44);e.exports=function(t,e){for(var n=t[i]||0,s=e[i]||0,u=-1;++u<n;){var a=t[r+u];void 0!==a&&(a[o]=e,e[r+(s+u)]=a,t[r+u]=void 0)}return e[i]=n+s,t[i]=void 0,e}},{33:33,43:43,44:44}],112:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){for(var e=-1,n=t[s]||0;++e<n;){var u=t[r+e];null!=u&&(u[o]=u[i]=t[r+e]=void 0)}return t[s]=void 0,t}},{33:33,42:42,43:43,44:44}],113:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){var e=t[o];if(e){for(var n=(t[i]||0)-1,u=(e[s]||0)-1;++n<=u;)e[r+n]=e[r+(n+1)];e[s]=u,t[i]=t[o]=e=void 0}return t}},{33:33,42:42,43:43,44:44}],114:[function(t,e,n){var r=t(43),o=t(39),i=t(46),s=t(44);e.exports=function(t,e){var n=[t],u=0;do{var a=n[u--];if(a&&a[i]!==e){a[i]=e,n[u++]=a[o];for(var c=-1,p=a[s]||0;++c<p;)n[u++]=a[r+c]}}while(u>-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(;c<u.length;){var t=c;if(c+=1,u[t].call(),c>p){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);
3459 break;case r.space:break;case r.closingBracket:h=!0;break;case r.quote:u(t,p,n,c);break;case r.openingBracket:o.throwError(i.nested,t);break;case r.commaSeparator:++f;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;p=t.next()}0===n.indexer.length&&o.throwError(i.empty,t),n.indexer.length>1&&l&&o.throwError(i.routedTokens,t),1===n.indexer.length&&(n.indexer=n.indexer[0]),c[c.length]=n.indexer,n.indexer=void 0}},{132:132,133:133,137:137,138:138,139:139}],137:[function(t,e,n){var r=t(132),o=t(133),i=o.quote;e.exports=function(t,e,n,s){for(var u=t.next(),a="",c=e.token,p=!1,h=!1;!u.done;){switch(u.type){case r.token:case r.space:case r.dotSeparator:case r.commaSeparator:case r.openingBracket:case r.closingBracket:case r.openingBrace:case r.closingBrace:p&&o.throwError(i.illegalEscape,t),a+=u.token;break;case r.quote:p?(a+=u.token,p=!1):u.token!==c?a+=u.token:h=!0;break;case r.escape:p=!0;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;u=t.next()}0===a.length&&o.throwError(i.empty,t),n.indexer[n.indexer.length]=a}},{132:132,133:133}],138:[function(t,e,n){var r=t(140),o=t(132),i=t(133);e.exports=function(t,e,n,s){var u,a=t.peek(),c=1,p=!1,h=!0,f=n.indexer.length-1,l=r.toNumber(n.indexer[f]);for(isNaN(l)&&i.throwError(i.range.precedingNaN,t);!p&&!a.done;){switch(a.type){case o.dotSeparator:3===c&&i.throwError(i.unexpectedToken,t),++c,3===c&&(h=!1);break;case o.token:u=r.toNumber(t.next().token),isNaN(u)&&i.throwError(i.range.suceedingNaN,t),p=!0;break;default:p=!0}if(p)break;t.next(),a=t.peek()}n.indexer[f]={from:l,to:h?u:u-1}}},{132:132,133:133,140:140}],139:[function(t,e,n){var r=t(132),o=t(131),i=t(133),s=i.routed;e.exports=function(t,e,n,u){var a=t.next(),c=!1,p="";switch(a.token){case o.integers:case o.ranges:case o.keys:break;default:i.throwError(s.invalid,t)}var h=t.next();if(h.type===r.colon&&(c=!0,h=t.next(),h.type!==r.token&&i.throwError(s.invalid,t),p=h.token,h=t.next()),h.type===r.closingBrace){var f={type:a.token,named:c,name:p};n.indexer[n.indexer.length]=f}else i.throwError(s.invalid,t)}},{131:131,132:132,133:133}],140:[function(t,e,n){function r(t,e,n){return{token:t,done:n,type:e}}function o(t,e,n){var o,g=!1,w="",x=n?m:b;do{if(o=e+1>=t.length)break;var _=t[e+1];if(void 0===_||-1!==x.indexOf(_)){if(w.length)break;++e;var S;switch(_){case s:S=i.dotSeparator;break;case u:S=i.commaSeparator;break;case a:S=i.openingBracket;break;case c:S=i.closingBracket;break;case p:S=i.openingBrace;break;case h:S=i.closingBrace;break;case y:S=i.space;break;case d:case v:S=i.quote;break;case l:S=i.escape;break;case f:S=i.colon;break;default:S=i.unknown}g=r(_,S,!1);break}w+=_,++e}while(!o);return!g&&w.length&&(g=r(w,i.token,!1)),g||(g={done:!0}),{token:g,idx:e}}var i=t(132),s=".",u=",",a="[",c="]",p="{",h="}",f=":",l="\\",d='"',v="'",y=" ",b="\\'\"[]., ",m="\\{}'\"[]., :",g=e.exports=function(t,e){this._string=t,this._idx=-1,this._extended=e,this.parseString=""};g.prototype={next:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._idx=t.idx,this._nextToken=!1,this.parseString+=t.token.token,t.token},peek:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._nextToken=t,t.token}},g.toNumber=function(t){return isNaN(+t)?NaN:+t}},{132:132}],141:[function(t,e,n){var r=t(147),o=t(148);e.exports=function(t){var e=t.reduce(function(t,e){var n=e.length;return t[n]||(t[n]=[]),t[n].push(e),t},{});return Object.keys(e).forEach(function(t){e[t]=o(e[t])}),r(e)}},{147:147,148:148}],142:[function(t,e,n){var r=t(144);e.exports=function o(t,e,n){for(var i=t,s=!0;s&&n<e.length;++n){var u=e[n],a=typeof u;if(u&&"object"===a){var c={},p=r(u,c),h=n+1;do{var f=i[p];s=void 0!==f,s&&(s=o(f,e,h)),p=r(u,c)}while(s&&!c.done);break}i=i[u],s=void 0!==i}return s}},{144:144}],143:[function(t,e,n){e.exports={iterateKeySet:t(144),toTree:t(148),toTreeWithUnion:t(149),pathsComplementFromTree:t(146),pathsComplementFromLengthTree:t(145),hasIntersection:t(142),toPaths:t(147),collapse:t(141)}},{141:141,142:142,144:144,145:145,146:146,147:147,148:148,149:149}],144:[function(t,e,n){function r(t,e){var n=e.from=t.from||0,r=e.to=t.to||"number"==typeof t.length&&e.from+t.length-1||0;e.rangeOffset=e.from,e.loaded=!0,n>r&&(e.empty=!0)}function o(t,e){e.done=!1;var n=e.isObject=!(!t||"object"!=typeof t);e.isArray=n&&i(t),e.arrayOffset=0}var i=Array.isArray;e.exports=function(t,e){if(void 0===e.isArray&&o(t,e),e.isArray){var n;do{e.loaded&&e.rangeOffset>e.to&&(++e.arrayOffset,e.loaded=!1);var i=e.arrayOffset,s=t.length;if(i>=s){e.done=!0;break}var u=t[e.arrayOffset],a=typeof u;if("object"===a){if(e.loaded||r(u,e),e.empty)continue;n=e.rangeOffset++}else++e.arrayOffset,n=u}while(void 0===n);return n}return e.isObject?(e.loaded||r(t,e),e.rangeOffset>e.to?void(e.done=!0):e.rangeOffset++):(e.done=!0,t)}},{}],145:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i){var u=t[i];r(e[u.length],u,0)||(n[++o]=u)}return n}},{142:142}],146:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i)r(e,t[i],0)||(n[++o]=t[i]);return n}},{142:142}],147:[function(t,e,n){function r(t){return null!==t&&typeof t===f}function o(t,e,n){var r,i,s,u,h,f,l,d,v,y,b,m,g,w,x=c(String(e)),_=Object.create(null),S=[],E=-1,C=0,A=[],N=0;if(u=[],h=-1,n-1>e){for(f=a(t,u);++h<f;)r=u[h],i=o(t[r],e+1,n),s=i.code,_[s]?i=_[s]:(S[C++]=s,i=_[s]={keys:[],sets:i.sets}),x=c(x+r+s),p(r)&&i.keys.push(parseInt(r,10))||i.keys.push(r);for(;++E<C;)if(r=S[E],i=_[r],u=i.keys,f=u.length,f>0)for(l=i.sets,d=-1,v=l.length,g=u[0];++d<v;){for(y=l[d],b=-1,m=y.length,w=new Array(m+1),w[0]=f>1&&u||g;++b<m;)w[b+1]=y[b];A[N++]=w}}else for(f=a(t,u),f>1?A[N++]=[u]:A[N++]=u;++h<f;)x=c(x+u[h]);return{code:x,sets:A}}function i(t){for(var e=-1,n=t.length;++e<n;){var r=t[e];h(r)&&(t[e]=s(r))}return t}function s(t){for(var e=-1,n=t.length-1,r=n>0;++e<=n;){var o=t[e];if(!p(o)){r=!1;break}t[e]=parseInt(o,10)}if(r===!0){t.sort(u);var i=t[0],s=t[n];if(n>=s-i)return{from:i,to:s}}return t}function u(t,e){return t-e}function a(t,e,n){var r=0;for(var o in t)e[r++]=o;return r>1&&e.sort(n),r}function c(t){for(var e=5381,n=-1,r=t.length;++n<r;)e=(e<<5)+e+t.charCodeAt(n);return String(e)}function p(t){return!h(t)&&t-parseFloat(t)+1>=0}var h=Array.isArray,f="object";e.exports=function(t){var e,n=[],s=0;for(var u in t)if(p(u)&&r(e=t[u]))for(var a=o(e,0,parseInt(u,10)).sets,c=-1,h=a.length;++c<h;)n[s++]=i(a[c]);return n}},{}],148:[function(t,e,n){function r(t,e,n){var i,s=e[n],u={},a=n+1;i=o(s,u);do{var c=t[i];c||(a===e.length?t[i]=null:c=t[i]={}),a<e.length&&r(c,e,a),u.done||(i=o(s,u))}while(!u.done)}var o=t(144);Array.isArray;e.exports=function(t){return t.reduce(function(t,e){return r(t,e,0),t},{})}},{144:144}],149:[function(t,e,n){},{}],150:[function(t,e,n){function r(){p=!1,u.length?c=u.concat(c):h=-1,c.length&&o()}function o(){if(!p){var t=setTimeout(r);p=!0;for(var e=c.length;e;){for(u=c,c=[];++h<e;)u&&u[h].run();h=-1,e=c.length}u=null,p=!1,clearTimeout(t)}}function i(t,e){this.fun=t,this.array=e}function s(){}var u,a=e.exports={},c=[],p=!1,h=-1;a.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new i(t,e)),1!==c.length||p||setTimeout(o,0)},i.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=s,a.addListener=s,a.once=s,a.off=s,a.removeListener=s,a.removeAllListeners=s,a.emit=s,a.binding=function(t){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(t){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],151:[function(t,e,n){"use strict";e.exports=t(156)},{156:156}],152:[function(t,e,n){"use strict";function r(){}function o(t){try{return t.then}catch(e){return y=e,b}}function i(t,e){try{return t(e)}catch(n){return y=n,b}}function s(t,e,n){try{t(e,n)}catch(r){return y=r,b}}function u(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],t!==r&&d(t,this)}function a(t,e,n){return new t.constructor(function(o,i){var s=new u(r);s.then(o,i),c(t,new l(e,n,s))})}function c(t,e){for(;3===t._37;)t=t._12;return 0===t._37?void t._59.push(e):void v(function(){var n=1===t._37?e.onFulfilled:e.onRejected;if(null===n)return void(1===t._37?p(e.promise,t._12):h(e.promise,t._12));var r=i(n,t._12);r===b?h(e.promise,y):p(e.promise,r)})}function p(t,e){if(e===t)return h(t,new TypeError("A promise cannot be resolved with itself."));if(e&&("object"==typeof e||"function"==typeof e)){var n=o(e);if(n===b)return h(t,y);if(n===t.then&&e instanceof u)return t._37=3,t._12=e,void f(t);if("function"==typeof n)return void d(n.bind(e),t)}t._37=1,t._12=e,f(t)}function h(t,e){t._37=2,t._12=e,f(t)}function f(t){for(var e=0;e<t._59.length;e++)c(t,t._59[e]);t._59=null}function l(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}function d(t,e){var n=!1,r=s(t,function(t){n||(n=!0,p(e,t))},function(t){n||(n=!0,h(e,t))});n||r!==b||(n=!0,h(e,y))}var v=t(124),y=null,b={};e.exports=u,u._99=r,u.prototype.then=function(t,e){if(this.constructor!==u)return a(this,t,e);var n=new u(r);return c(this,new l(t,e,n)),n}},{124:124}],153:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype.done=function(t,e){var n=arguments.length?this.then.apply(this,arguments):this;n.then(null,function(t){setTimeout(function(){throw t},0)})}},{152:152}],154:[function(t,e,n){"use strict";function r(t){var e=new o(o._99);return e._37=1,e._12=t,e}var o=t(152);e.exports=o;var i=r(!0),s=r(!1),u=r(null),a=r(void 0),c=r(0),p=r("");o.resolve=function(t){if(t instanceof o)return t;if(null===t)return u;if(void 0===t)return a;if(t===!0)return i;if(t===!1)return s;if(0===t)return c;if(""===t)return p;if("object"==typeof t||"function"==typeof t)try{var e=t.then;if("function"==typeof e)return new o(e.bind(t))}catch(n){return new o(function(t,e){e(n)})}return r(t)},o.all=function(t){var e=Array.prototype.slice.call(t);return new o(function(t,n){function r(s,u){if(u&&("object"==typeof u||"function"==typeof u)){if(u instanceof o&&u.then===o.prototype.then){for(;3===u._37;)u=u._12;return 1===u._37?r(s,u._12):(2===u._37&&n(u._12),void u.then(function(t){r(s,t)},n))}var a=u.then;if("function"==typeof a){var c=new o(a.bind(u));return void c.then(function(t){r(s,t)},n)}}e[s]=u,0===--i&&t(e)}if(0===e.length)return t([]);for(var i=e.length,s=0;s<e.length;s++)r(s,e[s])})},o.reject=function(t){return new o(function(e,n){n(t)})},o.race=function(t){return new o(function(e,n){t.forEach(function(t){o.resolve(t).then(e,n)})})},o.prototype["catch"]=function(t){return this.then(null,t)}},{152:152}],155:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype["finally"]=function(t){return this.then(function(e){return r.resolve(t()).then(function(){return e})},function(e){return r.resolve(t()).then(function(){throw e})})}},{152:152}],156:[function(t,e,n){"use strict";e.exports=t(152),t(153),t(155),t(154),t(157)},{152:152,153:153,154:154,155:155,157:157}],157:[function(t,e,n){"use strict";var r=t(152),o=t(123);e.exports=r,r.denodeify=function(t,e){return e=e||1/0,function(){var n=this,o=Array.prototype.slice.call(arguments,0,e>0?e:0);return new r(function(e,r){o.push(function(t,n){t?r(t):e(n)});var i=t.apply(n,o);!i||"object"!=typeof i&&"function"!=typeof i||"function"!=typeof i.then||e(i)})}},r.nodeify=function(t){return function(){var e=Array.prototype.slice.call(arguments),n="function"==typeof e[e.length-1]?e.pop():null,i=this;try{return t.apply(this,arguments).nodeify(n,i)}catch(s){if(null===n||"undefined"==typeof n)return new r(function(t,e){e(s)});o(function(){n.call(i,s)})}}},r.prototype.nodeify=function(t,e){return"function"!=typeof t?this:void this.then(function(n){o(function(){t.call(e,null,n)})},function(n){o(function(){t.call(e,n)})})}},{123:123,152:152}],158:[function(e,n,r){(function(o){(function(i){var s={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},u=s[typeof window]&&window||this,a=s[typeof r]&&r&&!r.nodeType&&r,c=s[typeof n]&&n&&!n.nodeType&&n,p=(c&&c.exports===a&&a,s[typeof o]&&o);!p||p.global!==p&&p.window!==p||(u=p),"function"==typeof t&&t.amd?t(["rx"],function(t,e){return i(u,e,t)}):"object"==typeof n&&n&&n.exports===a?n.exports=i(u,n.exports,e(159)):u.Rx=i(u,{},u.Rx)}).call(this,function(t,e,n,r){function o(){try{return l.apply(this,arguments)}catch(t){return M.e=t,M}}function i(t){if(!E(t))throw new TypeError("fn must be a function");return l=t,o}function s(t,e,n){return new b(function(r){var o=!1,i=null,s=[];return t.subscribe(function(t){var u,a;try{a=e(t)}catch(c){return void r.onError(c)}if(u=0,o)try{u=n(a,i)}catch(p){return void r.onError(p)}else o=!0,i=a;u>0&&(i=a,s=[]),u>=0&&s.push(t)},function(t){r.onError(t)},function(){r.onNext(s),r.onCompleted()})},t)}function u(t){if(0===t.length)throw new D;return t[0]}function a(t,e,n,r){if(0>e)throw new R;return new b(function(o){var i=e;return t.subscribe(function(t){0===i--&&(o.onNext(t),o.onCompleted())},function(t){o.onError(t)},function(){n?(o.onNext(r),o.onCompleted()):o.onError(new R)})},t)}function c(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){i?r.onError(new Error("Sequence contains more than one element")):(o=t,i=!0)},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function p(t,e,n){return new b(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},function(t){r.onError(t)},function(){e?(r.onNext(n),r.onCompleted()):r.onError(new D)})},t)}function h(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){o=t,i=!0},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function f(t,e,n,o){var i=j(e,n,3);return new b(function(e){var n=0;return t.subscribe(function(r){var s;try{s=i(r,n,t)}catch(u){return void e.onError(u)}s?(e.onNext(o?n:r),e.onCompleted()):n++},function(t){e.onError(t)},function(){e.onNext(o?-1:r),e.onCompleted()})},t)}var l,d=n.Observable,v=d.prototype,y=n.CompositeDisposable,b=n.AnonymousObservable,m=n.Disposable.empty,g=(n.internals.isEqual,n.helpers),w=g.not,x=g.defaultComparer,_=g.identity,S=g.defaultSubComparer,E=g.isFunction,C=g.isPromise,A=g.isArrayLike,N=g.isIterable,k=n.internals.inherits,O=d.fromPromise,P=d.from,j=n.internals.bindCallback,D=n.EmptyError,q=n.ObservableBase,R=n.ArgumentOutOfRangeError,M={e:{}};v.aggregate=function(){var t,e,n=!1,r=this;return 2===arguments.length?(n=!0,e=arguments[0],t=arguments[1]):t=arguments[0],new b(function(o){var i,s,u;return r.subscribe(function(r){!u&&(u=!0);try{i?s=t(s,r):(s=n?t(e,r):r,i=!0)}catch(a){return o.onError(a)}},function(t){o.onError(t)},function(){u&&o.onNext(s),!u&&n&&o.onNext(e),!u&&!n&&o.onError(new D),o.onCompleted()})},r)};var T=function(t){function e(e,n,r,o){this.source=e,this.acc=n,this.hasSeed=r,this.seed=o,t.call(this)}function n(t,e){this.o=t,this.acc=e.acc,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.result=null,this.hasValue=!1,this.isStopped=!1}return k(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this))},n.prototype.onNext=function(t){this.isStopped||(!this.hasValue&&(this.hasValue=!0),this.hasAccumulation?this.result=i(this.acc)(this.result,t):(this.result=this.hasSeed?i(this.acc)(this.seed,t):t,this.hasAccumulation=!0),this.result===M&&this.o.onError(this.result.e))},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.hasValue&&this.o.onNext(this.result),!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed),!this.hasValue&&!this.hasSeed&&this.o.onError(new D),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}(q);return v.reduce=function(t){var e=!1;if(2===arguments.length){e=!0;var n=arguments[1]}return new T(this,t,e,n)},v.some=function(t,e){var n=this;return t?n.filter(t,e).some():new b(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},function(e){t.onError(e)},function(){t.onNext(!1),t.onCompleted()})},n)},v.any=function(){return this.some.apply(this,arguments)},v.isEmpty=function(){return this.any().map(w)},v.every=function(t,e){return this.filter(function(e){return!t(e)},e).some().map(w)},v.all=function(){return this.every.apply(this,arguments)},v.includes=function(t,e){function n(t,e){return 0===t&&0===e||t===e||isNaN(t)&&isNaN(e)}var r=this;return new b(function(o){var i=0,s=+e||0;return Math.abs(s)===1/0&&(s=0),0>s?(o.onNext(!1),o.onCompleted(),m):r.subscribe(function(e){i++>=s&&n(e,t)&&(o.onNext(!0),o.onCompleted())},function(t){o.onError(t)},function(){o.onNext(!1),o.onCompleted()})},this)},v.contains=function(t,e){v.includes(t,e)},v.count=function(t,e){return t?this.filter(t,e).count():this.reduce(function(t){return t+1},0)},v.indexOf=function(t,e){var n=this;return new b(function(r){var o=0,i=+e||0;return Math.abs(i)===1/0&&(i=0),0>i?(r.onNext(-1),r.onCompleted(),m):n.subscribe(function(e){o>=i&&e===t&&(r.onNext(o),r.onCompleted()),o++},function(t){r.onError(t)},function(){r.onNext(-1),r.onCompleted()})},n)},v.sum=function(t,e){return t&&E(t)?this.map(t,e).sum():this.reduce(function(t,e){return t+e},0)},v.minBy=function(t,e){return e||(e=S),s(this,t,function(t,n){return-1*e(t,n)})},v.min=function(t){return this.minBy(_,t).map(function(t){return u(t)})},v.maxBy=function(t,e){return e||(e=S),s(this,t,e)},v.max=function(t){return this.maxBy(_,t).map(function(t){return u(t)})},v.average=function(t,e){return t&&E(t)?this.map(t,e).average():this.reduce(function(t,e){return{sum:t.sum+e,count:t.count+1}},{sum:0,count:0}).map(function(t){if(0===t.count)throw new D;return t.sum/t.count})},v.sequenceEqual=function(t,e){var n=this;return e||(e=x),new b(function(r){var o=!1,i=!1,s=[],u=[],a=n.subscribe(function(t){var n,o;if(u.length>0){o=u.shift();try{n=e(o,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else i?(r.onNext(!1),r.onCompleted()):s.push(t)},function(t){r.onError(t)},function(){o=!0,0===s.length&&(u.length>0?(r.onNext(!1),r.onCompleted()):i&&(r.onNext(!0),r.onCompleted()))});(A(t)||N(t))&&(t=P(t)),C(t)&&(t=O(t));var c=t.subscribe(function(t){var n;if(s.length>0){var i=s.shift();try{n=e(i,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else o?(r.onNext(!1),r.onCompleted()):u.push(t)},function(t){r.onError(t)},function(){i=!0,0===u.length&&(s.length>0?(r.onNext(!1),r.onCompleted()):o&&(r.onNext(!0),r.onCompleted()))});return new y(a,c)},n)},v.elementAt=function(t){return a(this,t,!1)},v.elementAtOrDefault=function(t,e){return a(this,t,!0,e)},v.single=function(t,e){return t&&E(t)?this.where(t,e).single():c(this,!1)},v.singleOrDefault=function(t,e,n){return t&&E(t)?this.filter(t,n).singleOrDefault(null,e):c(this,!0,e)},v.first=function(t,e){return t?this.where(t,e).first():p(this,!1)},v.firstOrDefault=function(t,e,n){return t?this.where(t).firstOrDefault(null,e):p(this,!0,e)},v.last=function(t,e){return t?this.where(t,e).last():h(this,!1)},v.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):h(this,!0,e)},v.find=function(t,e){return f(this,t,e,!1)},v.findIndex=function(t,e){return f(this,t,e,!0)},v.toSet=function(){if("undefined"==typeof t.Set)throw new TypeError;var e=this;return new b(function(n){var r=new t.Set;return e.subscribe(function(t){r.add(t)},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},v.toMap=function(e,n){if("undefined"==typeof t.Map)throw new TypeError;var r=this;return new b(function(o){var i=new t.Map;return r.subscribe(function(t){var r;try{r=e(t)}catch(s){return void o.onError(s)}var u=t;if(n)try{u=n(t)}catch(s){return void o.onError(s)}i.set(r,u)},function(t){o.onError(t)},function(){o.onNext(i),o.onCompleted()})},r)},n})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{159:159}],159:[function(e,n,r){(function(e,o){(function(i){function u(t){for(var e=[],n=0,r=t.length;r>n;n++)e.push(t[n]);return e}function a(t,e){if(ct&&e.stack&&"object"==typeof t&&null!==t&&t.stack&&-1===t.stack.indexOf(lt)){for(var n=[],r=e;r;r=r.source)r.stack&&n.unshift(r.stack);n.unshift(t.stack);var o=n.join("\n"+lt+"\n");t.stack=c(o)}}function c(t){for(var e=t.split("\n"),n=[],r=0,o=e.length;o>r;r++){var i=e[r];p(i)||h(i)||!i||n.push(i)}return n.join("\n")}function p(t){var e=l(t);if(!e)return!1;var n=e[0],r=e[1];return n===ht&&r>=ft&&$n>=r}function h(t){return-1!==t.indexOf("(module.js:")||-1!==t.indexOf("(node.js:")}function f(){if(ct)try{throw new Error}catch(t){var e=t.stack.split("\n"),n=e[0].indexOf("@")>0?e[1]:e[2],r=l(n);if(!r)return;return ht=r[0],r[1]}}function l(t){var e=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(t);if(e)return[e[1],Number(e[2])];var n=/at ([^ ]+):(\d+):(?:\d+)$/.exec(t);if(n)return[n[1],Number(n[2])];var r=/.*@(.+):(\d+)$/.exec(t);return r?[r[1],Number(r[2])]:void 0}function d(t){var e=[];if(!Ht(t))return e;Ut.nonEnumArgs&&t.length&&Xt(t)&&(t=Yt.call(t));var n=Ut.enumPrototypes&&"function"==typeof t,r=Ut.enumErrorProps&&(t===Jt||t instanceof Error);for(var o in t)n&&"prototype"==o||r&&("message"==o||"name"==o)||e.push(o);if(Ut.nonEnumShadows&&t!==It){var i=t.constructor,s=-1,u=kt;if(t===(i&&i.prototype))var a=t===Lt?$t:t===Jt?qt:Wt.call(t),c=Ft[a];for(;++s<u;)o=Nt[s],c&&c[o]||!zt.call(t,o)||e.push(o)}return e}function v(t,e,n){for(var r=-1,o=n(t),i=o.length;++r<i;){var s=o[r];if(e(t[s],s,t)===!1)break}return t}function y(t,e){return v(t,e,d)}function b(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function m(t,e,n,r){if(t===e)return 0!==t||1/t==1/e;var o=typeof t,i=typeof e;if(t===t&&(null==t||null==e||"function"!=o&&"object"!=o&&"function"!=i&&"object"!=i))return!1;var s=Wt.call(t),u=Wt.call(e);if(s==Ot&&(s=Tt),u==Ot&&(u=Tt),s!=u)return!1;switch(s){case jt:case Dt:return+t==+e;case Mt:return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case Vt:case $t:return t==String(e)}var a=s==Pt;if(!a){if(s!=Tt||!Ut.nodeClass&&(b(t)||b(e)))return!1;var c=!Ut.argsObject&&Xt(t)?Object:t.constructor,p=!Ut.argsObject&&Xt(e)?Object:e.constructor;if(!(c==p||zt.call(t,"constructor")&&zt.call(e,"constructor")||at(c)&&c instanceof c&&at(p)&&p instanceof p||!("constructor"in t&&"constructor"in e)))return!1}n||(n=[]),r||(r=[]);for(var h=n.length;h--;)if(n[h]==t)return r[h]==e;var f=0,l=!0;if(n.push(t),r.push(e),a){if(h=t.length,f=e.length,l=f==h)for(;f--;){var d=e[f];if(!(l=m(t[f],d,n,r)))break}}else y(e,function(e,o,i){return zt.call(i,o)?(f++,l=zt.call(t,o)&&m(t[o],e,n,r)):void 0}),l&&y(t,function(t,e,n){return zt.call(n,e)?l=--f>-1:void 0});return n.pop(),r.pop(),l}function g(t,e){for(var n=new Array(t),r=0;t>r;r++)n[r]=e();return n}function w(){try{return Qt.apply(this,arguments)}catch(t){return ne.e=t,ne}}function x(t){if(!at(t))throw new TypeError("fn must be a function");return Qt=t,w}function _(t){throw t}function S(t,e){this.id=t,this.value=e}function E(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function C(t,e){e.isDisposed||(e.isDisposed=!0,e.disposable.dispose())}function A(t){this._s=s}function N(t){this._s=s,this._l=s.length,this._i=0}function k(t){this._a=t}function O(t){this._a=t,this._l=q(t),this._i=0}function P(t){return"number"==typeof t&&X.isFinite(t)}function j(t){var e,n=t[xt];if(!n&&"string"==typeof t)return e=new A(t),e[xt]();if(!n&&t.length!==i)return e=new k(t),e[xt]();if(!n)throw new TypeError("Object is not iterable");return t[xt]()}function D(t){var e=+t;return 0===e?e:isNaN(e)?e:0>e?-1:1}function q(t){var e=+t.length;return isNaN(e)?0:0!==e&&P(e)?(e=D(e)*Math.floor(Math.abs(e)),0>=e?0:e>en?en:e):e}function R(t,e){this.observer=t,this.parent=e}function M(t,e){return me(t)||(t=_e),new rn(e,t)}function T(t,e){this.observer=t,this.parent=e}function V(t,e){this.observer=t,this.parent=e}function $(t,e){return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.subscribe(function(t){n.onNext(t)},function(t){try{var r=e(t)}catch(i){return n.onError(i)}ut(r)&&(r=Xe(r));var s=new fe;o.setDisposable(s),s.setDisposable(r.subscribe(n))},function(t){n.onCompleted(t)})),o},t)}function W(){return!1}function z(t,e){var n=this;return new qn(function(r){var o=0,i=t.length;return n.subscribe(function(n){if(i>o){var s=t[o++],u=x(e)(n,s);if(u===ne)return r.onError(u.e);r.onNext(u)}else r.onCompleted()},function(t){r.onError(t)},function(){r.onCompleted()})},n)}function W(){return!1}function G(){return[]}function W(){return!1}function J(){return[]}function I(t,e){this.observer=t,this.accumulator=e.accumulator,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.accumulation=null,this.hasValue=!1,this.isStopped=!1}function L(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).concatAll()}function B(t,e,n){for(var r=0,o=t.length;o>r;r++)if(n(t[r],e))return r;return-1}function F(t){this.comparer=t,this.set=[]}function U(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).mergeAll()}var H={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X=H[typeof window]&&window||this,Q=H[typeof r]&&r&&!r.nodeType&&r,K=H[typeof n]&&n&&!n.nodeType&&n,Y=K&&K.exports===Q&&Q,Z=H[typeof o]&&o;!Z||Z.global!==Z&&Z.window!==Z||(X=Z);var tt={internals:{},config:{Promise:X.Promise},helpers:{}},et=tt.helpers.noop=function(){},nt=(tt.helpers.notDefined=function(t){return"undefined"==typeof t},tt.helpers.identity=function(t){return t}),rt=(tt.helpers.pluck=function(t){return function(e){return e[t]}},tt.helpers.just=function(t){return function(){return t}},tt.helpers.defaultNow=Date.now),ot=tt.helpers.defaultComparer=function(t,e){return Kt(t,e)},it=tt.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},st=(tt.helpers.defaultKeySerializer=function(t){return t.toString()},tt.helpers.defaultError=function(t){throw t}),ut=tt.helpers.isPromise=function(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then},at=(tt.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},tt.helpers.not=function(t){return!t},tt.helpers.isFunction=function(){var t=function(t){return"function"==typeof t||!1};return t(/x/)&&(t=function(t){return"function"==typeof t&&"[object Function]"==Wt.call(t)}),t}());tt.config.longStackSupport=!1;var ct=!1;try{throw new Error}catch(pt){ct=!!pt.stack}var ht,ft=f(),lt="From previous event:",dt=tt.EmptyError=function(){this.message="Sequence contains no elements.",Error.call(this)};dt.prototype=Error.prototype;var vt=tt.ObjectDisposedError=function(){this.message="Object has been disposed",Error.call(this)};vt.prototype=Error.prototype;var yt=tt.ArgumentOutOfRangeError=function(){this.message="Argument out of range",Error.call(this)};yt.prototype=Error.prototype;var bt=tt.NotSupportedError=function(t){this.message=t||"This operation is not supported",Error.call(this)};bt.prototype=Error.prototype;var mt=tt.NotImplementedError=function(t){this.message=t||"This operation is not implemented",Error.call(this)};mt.prototype=Error.prototype;var gt=tt.helpers.notImplemented=function(){throw new mt},wt=tt.helpers.notSupported=function(){throw new bt},xt="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";X.Set&&"function"==typeof(new X.Set)["@@iterator"]&&(xt="@@iterator");var _t=tt.doneEnumerator={done:!0,value:i},St=tt.helpers.isIterable=function(t){return t[xt]!==i},Et=tt.helpers.isArrayLike=function(t){return t&&t.length!==i};tt.helpers.iterator=xt;var Ct,At=tt.internals.bindCallback=function(t,e,n){if("undefined"==typeof e)return t;switch(n){case 0:return function(){return t.call(e)};case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}},Nt=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],kt=Nt.length,Ot="[object Arguments]",Pt="[object Array]",jt="[object Boolean]",Dt="[object Date]",qt="[object Error]",Rt="[object Function]",Mt="[object Number]",Tt="[object Object]",Vt="[object RegExp]",$t="[object String]",Wt=Object.prototype.toString,zt=Object.prototype.hasOwnProperty,Gt=Wt.call(arguments)==Ot,Jt=Error.prototype,It=Object.prototype,Lt=String.prototype,Bt=It.propertyIsEnumerable;try{Ct=!(Wt.call(document)==Tt&&!({toString:0}+""))}catch(pt){Ct=!0}var Ft={};Ft[Pt]=Ft[Dt]=Ft[Mt]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Ft[jt]=Ft[$t]={constructor:!0,toString:!0,valueOf:!0},Ft[qt]=Ft[Rt]=Ft[Vt]={constructor:!0,toString:!0},Ft[Tt]={constructor:!0};var Ut={};!function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);Ut.enumErrorProps=Bt.call(Jt,"message")||Bt.call(Jt,"name"),Ut.enumPrototypes=Bt.call(t,"prototype"),Ut.nonEnumArgs=0!=n,Ut.nonEnumShadows=!/valueOf/.test(e)}(1);var Ht=tt.internals.isObject=function(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1},Xt=function(t){return t&&"object"==typeof t?Wt.call(t)==Ot:!1};Gt||(Xt=function(t){return t&&"object"==typeof t?zt.call(t,"callee"):!1});var Qt,Kt=tt.internals.isEqual=function(t,e){return m(t,e,[],[])},Yt=({}.hasOwnProperty,Array.prototype.slice),Zt=this.inherits=tt.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},te=tt.internals.addProperties=function(t){for(var e=[],n=1,r=arguments.length;r>n;n++)e.push(arguments[n]);for(var o=0,i=e.length;i>o;o++){var s=e[o];for(var u in s)t[u]=s[u]}},ee=tt.internals.addRef=function(t,e){return new qn(function(n){return new ie(e.getDisposable(),t.subscribe(n))})},ne={e:{}};S.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var re=tt.internals.PriorityQueue=function(t){this.items=new Array(t),this.length=0},oe=re.prototype;oe.isHigherPriority=function(t,e){return this.items[t].compareTo(this.items[e])<0},oe.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},oe.heapify=function(t){if(+t||(t=0),!(t>=this.length||0>t)){var e=2*t+1,n=2*t+2,r=t;if(e<this.length&&this.isHigherPriority(e,r)&&(r=e),n<this.length&&this.isHigherPriority(n,r)&&(r=n),r!==t){var o=this.items[t];this.items[t]=this.items[r],this.items[r]=o,this.heapify(r)}}},oe.peek=function(){return this.items[0].value},oe.removeAt=function(t){this.items[t]=this.items[--this.length],this.items[this.length]=i,this.heapify()},oe.dequeue=function(){var t=this.peek();return this.removeAt(0),t},oe.enqueue=function(t){var e=this.length++;this.items[e]=new S(re.count++,t),this.percolate(e)},oe.remove=function(t){for(var e=0;e<this.length;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},re.count=0;var ie=tt.CompositeDisposable=function(){var t,e,n=[];if(Array.isArray(arguments[0]))n=arguments[0],e=n.length;else for(e=arguments.length,n=new Array(e),t=0;e>t;t++)n[t]=arguments[t];for(t=0;e>t;t++)if(!pe(n[t]))throw new TypeError("Not a disposable");this.disposables=n,this.isDisposed=!1,this.length=n.length},se=ie.prototype;se.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},se.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},se.dispose=function(){
3460 if(!this.isDisposed){this.isDisposed=!0;for(var t=this.disposables.length,e=new Array(t),n=0;t>n;n++)e[n]=this.disposables[n];for(this.disposables=[],this.length=0,n=0;t>n;n++)e[n].dispose()}};var ue=tt.Disposable=function(t){this.isDisposed=!1,this.action=t||et};ue.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ae=ue.create=function(t){return new ue(t)},ce=ue.empty={dispose:et},pe=ue.isDisposable=function(t){return t&&at(t.dispose)},he=ue.checkDisposed=function(t){if(t.isDisposed)throw new vt},fe=tt.SingleAssignmentDisposable=function(){this.isDisposed=!1,this.current=null};fe.prototype.getDisposable=function(){return this.current},fe.prototype.setDisposable=function(t){if(this.current)throw new Error("Disposable has already been assigned");var e=this.isDisposed;!e&&(this.current=t),e&&t&&t.dispose()},fe.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var le=tt.SerialDisposable=function(){this.isDisposed=!1,this.current=null};le.prototype.getDisposable=function(){return this.current},le.prototype.setDisposable=function(t){var e=this.isDisposed;if(!e){var n=this.current;this.current=t}n&&n.dispose(),e&&t&&t.dispose()},le.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var de=tt.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?ce:new t(this)},e}();E.prototype.dispose=function(){this.scheduler.scheduleWithState(this,C)};var ve=tt.internals.ScheduledItem=function(t,e,n,r,o){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=o||it,this.disposable=new fe};ve.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ve.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},ve.prototype.isCancelled=function(){return this.disposable.isDisposed},ve.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var ye=tt.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){return e(),ce}t.isScheduler=function(e){return e instanceof t};var n=t.prototype;return n.schedule=function(t){return this._schedule(t,e)},n.scheduleWithState=function(t,e){return this._schedule(t,e)},n.scheduleWithRelative=function(t,n){return this._scheduleRelative(n,t,e)},n.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},n.scheduleWithAbsolute=function(t,n){return this._scheduleAbsolute(n,t,e)},n.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},t.now=rt,t.normalize=function(t){return 0>t&&(t=0),t},t}(),be=ye.normalize,me=ye.isScheduler;!function(t){function e(t,e){function n(e){o(e,function(e){var r=!1,o=!1,s=t.scheduleWithState(e,function(t,e){return r?i.remove(s):o=!0,n(e),ce});o||(i.add(s),r=!0)})}var r=e[0],o=e[1],i=new ie;return n(r),i}function n(t,e,n){function r(e){i(e,function(e,o){var i=!1,u=!1,a=t[n](e,o,function(t,e){return i?s.remove(a):u=!0,r(e),ce});u||(s.add(a),i=!0)})}var o=e[0],i=e[1],s=new ie;return r(o),s}function r(t,e){t(function(n){e(t,n)})}t.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,r)},t.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState([t,n],e)},t.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,r)},t.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative([t,r],e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},t.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,r)},t.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute([t,r],e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})}}(ye.prototype),function(t){ye.prototype.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,e)},ye.prototype.schedulePeriodicWithState=function(t,e,n){if("undefined"==typeof X.setInterval)throw new bt;e=be(e);var r=t,o=X.setInterval(function(){r=n(r)},e);return ae(function(){X.clearInterval(o)})}}(ye.prototype),function(t){t.catchError=t["catch"]=function(t){return new Ae(this,t)}}(ye.prototype);var ge,we,xe=(tt.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new fe;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}(),ye.immediate=function(){function t(t,e){return e(this,t)}return new ye(rt,t,wt,wt)}()),_e=ye.currentThread=function(){function t(){for(;n.length>0;){var t=n.dequeue();!t.isCancelled()&&t.invoke()}}function e(e,r){var o=new ve(this,e,r,this.now());if(n)n.enqueue(o);else{n=new re(4),n.enqueue(o);var i=x(t)();if(n=null,i===ne)return _(i.e)}return o.disposable}var n,r=new ye(rt,e,wt,wt);return r.scheduleRequired=function(){return!n},r}(),Se=function(){var t,e=et;if(X.setTimeout)t=X.setTimeout,e=X.clearTimeout;else{if(!X.WScript)throw new bt;t=function(t,e){X.WScript.Sleep(e),t()}}return{setTimeout:t,clearTimeout:e}}(),Ee=Se.setTimeout,Ce=Se.clearTimeout;!function(){function t(e){if(s)Ee(function(){t(e)},0);else{var n=i[e];if(n){s=!0;var r=x(n)();if(we(e),s=!1,r===ne)return _(r.e)}}}function n(){if(!X.postMessage||X.importScripts)return!1;var t=!1,e=X.onmessage;return X.onmessage=function(){t=!0},X.postMessage("","*"),X.onmessage=e,t}function r(e){"string"==typeof e.data&&e.data.substring(0,c.length)===c&&t(e.data.substring(c.length))}var o=1,i={},s=!1;we=function(t){delete i[t]};var u=RegExp("^"+String(Wt).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),a="function"==typeof(a=Z&&Y&&Z.setImmediate)&&!u.test(a)&&a;if(at(a))ge=function(e){var n=o++;return i[n]=e,a(function(){t(n)}),n};else if("undefined"!=typeof e&&"[object process]"==={}.toString.call(e))ge=function(n){var r=o++;return i[r]=n,e.nextTick(function(){t(r)}),r};else if(n()){var c="ms.rx.schedule"+Math.random();X.addEventListener?X.addEventListener("message",r,!1):X.attachEvent?X.attachEvent("onmessage",r):X.onmessage=r,ge=function(t){var e=o++;return i[e]=t,X.postMessage(c+currentId,"*"),e}}else if(X.MessageChannel){var p=new X.MessageChannel;p.port1.onmessage=function(e){t(e.data)},ge=function(t){var e=o++;return i[e]=t,p.port2.postMessage(e),e}}else ge="document"in X&&"onreadystatechange"in X.document.createElement("script")?function(e){var n=X.document.createElement("script"),r=o++;return i[r]=e,n.onreadystatechange=function(){t(r),n.onreadystatechange=null,n.parentNode.removeChild(n),n=null},X.document.documentElement.appendChild(n),r}:function(e){var n=o++;return i[n]=e,Ee(function(){t(n)},0),n}}();var Ae=(ye.timeout=ye["default"]=function(){function t(t,e){var n=this,r=new fe,o=ge(function(){!r.isDisposed&&r.setDisposable(e(n,t))});return new ie(r,ae(function(){we(o)}))}function e(t,e,n){var r=this,o=ye.normalize(e),i=new fe;if(0===o)return r.scheduleWithState(t,n);var s=Ee(function(){!i.isDisposed&&i.setDisposable(n(r,t))},o);return new ie(i,ae(function(){Ce(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new ye(rt,t,e,n)}(),function(t){function e(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function n(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function r(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,i){this._scheduler=o,this._handler=i,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,this._scheduler.now.bind(this._scheduler),e,n,r)}return Zt(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(o){if(!e._handler(o))throw o;return ce}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,o=!1,i=new fe;return i.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(o)return null;try{return n(t)}catch(e){if(o=!0,!r._handler(e))throw e;return i.dispose(),null}})),i},o}(ye)),Ne=tt.Notification=function(){function t(t,e,n,r,o,i){this.kind=t,this.value=e,this.exception=n,this._accept=r,this._acceptObservable=o,this.toString=i}return t.prototype.accept=function(t,e,n){return t&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},t.prototype.toObservable=function(t){var e=this;return me(t)||(t=xe),new qn(function(n){return t.scheduleWithState(e,function(t,e){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),ke=Ne.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){return new Ne("N",r,null,t,e,n)}}(),Oe=Ne.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){return new Ne("E",null,r,t,e,n)}}(),Pe=Ne.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){return new Ne("C",null,null,t,e,n)}}(),je=tt.Observer=function(){};je.prototype.toNotifier=function(){var t=this;return function(e){return e.accept(t)}},je.prototype.asObserver=function(){return new Me(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))},je.prototype.checked=function(){return new Te(this)};var De=je.create=function(t,e,n){return t||(t=et),e||(e=st),n||(n=et),new Me(t,e,n)};je.fromNotifier=function(t,e){return new Me(function(n){return t.call(e,ke(n))},function(n){return t.call(e,Oe(n))},function(){return t.call(e,Pe())})},je.prototype.notifyOn=function(t){return new $e(t,this)},je.prototype.makeSafe=function(t){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,t)};var qe,Re=tt.internals.AbstractObserver=function(t){function e(){this.isStopped=!1,t.call(this)}return Zt(e,t),e.prototype.next=gt,e.prototype.error=gt,e.prototype.completed=gt,e.prototype.onNext=function(t){this.isStopped||this.next(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.error(t))},e.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.completed())},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.error(t),!0)},e}(je),Me=tt.AnonymousObserver=function(t){function e(e,n,r){t.call(this),this._onNext=e,this._onError=n,this._onCompleted=r}return Zt(e,t),e.prototype.next=function(t){this._onNext(t)},e.prototype.error=function(t){this._onError(t)},e.prototype.completed=function(){this._onCompleted()},e}(Re),Te=function(t){function e(e){t.call(this),this._observer=e,this._state=0}Zt(e,t);var n=e.prototype;return n.onNext=function(t){this.checkAccess();var e=x(this._observer.onNext).call(this._observer,t);this._state=0,e===ne&&_(e.e)},n.onError=function(t){this.checkAccess();var e=x(this._observer.onError).call(this._observer,t);this._state=2,e===ne&&_(e.e)},n.onCompleted=function(){this.checkAccess();var t=x(this._observer.onCompleted).call(this._observer);this._state=2,t===ne&&_(t.e)},n.checkAccess=function(){if(1===this._state)throw new Error("Re-entrancy detected");if(2===this._state)throw new Error("Observer completed");0===this._state&&(this._state=1)},e}(je),Ve=tt.internals.ScheduledObserver=function(t){function e(e,n){t.call(this),this.scheduler=e,this.observer=n,this.isAcquired=!1,this.hasFaulted=!1,this.queue=[],this.disposable=new le}return Zt(e,t),e.prototype.next=function(t){var e=this;this.queue.push(function(){e.observer.onNext(t)})},e.prototype.error=function(t){var e=this;this.queue.push(function(){e.observer.onError(t)})},e.prototype.completed=function(){var t=this;this.queue.push(function(){t.observer.onCompleted()})},e.prototype.ensureActive=function(){var t=!1,e=this;!this.hasFaulted&&this.queue.length>0&&(t=!this.isAcquired,this.isAcquired=!0),t&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(t){var n;if(!(e.queue.length>0))return void(e.isAcquired=!1);n=e.queue.shift();try{n()}catch(r){throw e.queue=[],e.hasFaulted=!0,r}t()}))},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.disposable.dispose()},e}(Re),$e=function(t){function e(e,n,r){t.call(this,e,n),this._cancel=r}return Zt(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e.prototype.dispose=function(){t.prototype.dispose.call(this),this._cancel&&this._cancel.dispose(),this._cancel=null},e}(Ve),We=tt.Observable=function(){function t(t){if(tt.config.longStackSupport&&ct){try{throw new Error}catch(e){this.stack=e.stack.substring(e.stack.indexOf("\n")+1)}var n=this;this._subscribe=function(e){var r=e.onError.bind(e);return e.onError=function(t){a(t,n),r(t)},t.call(n,e)}}else this._subscribe=t}return qe=t.prototype,qe.subscribe=qe.forEach=function(t,e,n){return this._subscribe("object"==typeof t?t:De(t,e,n))},qe.subscribeOnNext=function(t,e){return this._subscribe(De("undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnError=function(t,e){return this._subscribe(De(null,"undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnCompleted=function(t,e){return this._subscribe(De(null,null,"undefined"!=typeof e?function(){t.call(e)}:t))},t}(),ze=tt.ObservableBase=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.subscribeCore).call(o,r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(t){var e=new Rn(t),r=[e,this];return _e.scheduleRequired()?_e.scheduleWithState(r,n):n(null,r),e}function o(){t.call(this,r)}return Zt(o,t),o.prototype.subscribeCore=gt,o}(We),Ge=tt.internals.Enumerable=function(){},Je=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e,n){this.o=t,this.s=e,this.e=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,r=new le,o=xe.scheduleRecursiveWithState(this.sources[xt](),function(o,i){if(!e){var s=x(o.next).call(o);if(s===ne)return t.onError(s.e);if(s.done)return t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(new n(t,i,o)))}});return new ie(r,o,ae(function(){e=!0}))},n.prototype.onNext=function(t){this.isStopped||this.o.onNext(t)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.s(this.e))},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);Ge.prototype.concat=function(){return new Je(this)};var Ie=function(t){function e(e){this.sources=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,n=this.sources[xt](),r=new le,o=xe.scheduleRecursiveWithState(null,function(o,i){if(!e){var s=x(n.next).call(n);if(s===ne)return t.onError(s.e);if(s.done)return null!==o?t.onError(o):t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(function(e){t.onNext(e)},i,function(){t.onCompleted()}))}});return new ie(r,o,ae(function(){e=!0}))},e}(ze);Ge.prototype.catchError=function(){return new Ie(this)},Ge.prototype.catchErrorWhen=function(t){var e=this;return new qn(function(n){var r,o,i=new Tn,s=new Tn,u=t(i),a=u.subscribe(s),c=e[xt](),p=new le,h=xe.scheduleRecursive(function(t){if(!r){var e=x(c.next).call(c);if(e===ne)return n.onError(e.e);if(e.done)return void(o?n.onError(o):n.onCompleted());var u=e.value;ut(u)&&(u=Xe(u));var a=new fe,h=new fe;p.setDisposable(new ie(h,a)),a.setDisposable(u.subscribe(function(t){n.onNext(t)},function(e){h.setDisposable(s.subscribe(t,function(t){n.onError(t)},function(){n.onCompleted()})),i.onNext(e)},function(){n.onCompleted()}))}});return new ie(a,p,h,ae(function(){r=!0}))})};var Le=function(t){function e(t,e){this.v=t,this.c=null==e?-1:e}function n(t){this.v=t.v,this.l=t.c}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return 0===this.l?_t:(this.l>0&&this.l--,{done:!1,value:this.v})},e}(Ge),Be=Ge.repeat=function(t,e){return new Le(t,e)},Fe=function(t){function e(t,e,n){this.s=t,this.fn=e?At(e,n,3):null}function n(t){this.i=-1,this.s=t.s,this.l=this.s.length,this.fn=t.fn}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return++this.i<this.l?{done:!1,value:this.fn?this.fn(this.s[this.i],this.i,this.s):this.s[this.i]}:_t},e}(Ge),Ue=Ge.of=function(t,e,n){return new Fe(t,e,n)};qe.observeOn=function(t){var e=this;return new qn(function(n){return e.subscribe(new $e(t,n))},e)},qe.subscribeOn=function(t){var e=this;return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.schedule(function(){o.setDisposable(new E(t,e.subscribe(n)))})),o},e)};var He=function(t){function e(e){this.p=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.p.then(function(e){t.onNext(e),t.onCompleted()},function(e){t.onError(e)}),ce},e}(ze),Xe=We.fromPromise=function(t){return new He(t)};qe.toPromise=function(t){if(t||(t=tt.config.Promise),!t)throw new bt("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,o=!1;e.subscribe(function(t){r=t,o=!0},n,function(){o&&t(r)})})};var Qe=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.a=[],this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=function(t){this.isStopped||this.a.push(t)},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.onNext(this.a),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.toArray=function(){return new Qe(this)},We.create=We.createWithDisposable=function(t,e){return new qn(t,e)};var Ke=(We.defer=function(t){return new qn(function(e){var n;try{n=t()}catch(r){return dn(r).subscribe(e)}return ut(n)&&(n=Xe(n)),n.subscribe(e)})},function(t){function e(e){this.scheduler=e,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){e.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState(this.observer,r)},e}(ze)),Ye=We.empty=function(t){return me(t)||(t=xe),new Ke(t)},Ze=function(t){function e(e,n,r){this.iterable=e,this.mapper=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new tn(t,this);return e.run()},e}(ze),tn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,e){try{var i=n.next()}catch(s){return r.onError(s)}if(i.done)return r.onCompleted();var u=i.value;if(o)try{u=o(u,t)}catch(s){return r.onError(s)}r.onNext(u),e(t+1)}var e=Object(this.parent.iterable),n=j(e),r=this.observer,o=this.parent.mapper;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}(),en=Math.pow(2,53)-1;A.prototype[xt]=function(){return new N(this._s)},N.prototype[xt]=function(){return this},N.prototype.next=function(){return this._i<this._l?{done:!1,value:this._s.charAt(this._i++)}:_t},k.prototype[xt]=function(){return new O(this._a)},O.prototype[xt]=function(){return this},O.prototype.next=function(){return this._i<this._l?{done:!1,value:this._a[this._i++]}:_t};var nn=We.from=function(t,e,n,r){if(null==t)throw new Error("iterable cannot be null.");if(e&&!at(e))throw new Error("mapFn when provided must be a function");if(e)var o=At(e,n,2);return me(r)||(r=_e),new Ze(t,o,r)},rn=function(t){function e(e,n){this.args=e,this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new R(t,this);return e.run()},e}(ze);R.prototype.run=function(){function t(t,o){r>t?(e.onNext(n[t]),o(t+1)):e.onCompleted()}var e=this.observer,n=this.parent.args,r=n.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)};var on=We.fromArray=function(t,e){return me(e)||(e=_e),new rn(t,e)};We.generate=function(t,e,n,r,o){return me(o)||(o=_e),new qn(function(i){var s=!0;return o.scheduleRecursiveWithState(t,function(t,o){var u,a;try{s?s=!1:t=n(t),u=e(t),u&&(a=r(t))}catch(c){return i.onError(c)}u?(i.onNext(a),o(t)):i.onCompleted()})})};var sn=function(t){function e(){t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return ce},e}(ze),un=We.never=function(){return new sn};We.of=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return new rn(e,_e)},We.ofWithScheduler=function(t){for(var e=arguments.length,n=new Array(e-1),r=1;e>r;r++)n[r-1]=arguments[r];return new rn(n,t)};var an=function(t){function e(e,n){this.obj=e,this.keys=Object.keys(e),this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new T(t,this);return e.run()},e}(ze);T.prototype.run=function(){function t(t,i){if(o>t){var s=r[t];e.onNext([s,n[s]]),i(t+1)}else e.onCompleted()}var e=this.observer,n=this.parent.obj,r=this.parent.keys,o=r.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},We.pairs=function(t,e){return e||(e=_e),new an(t,e)};var cn=function(t){function e(e,n,r){this.start=e,this.rangeCount=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new pn(t,this);return e.run()},e}(ze),pn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,o){n>t?(r.onNext(e+t),o(t+1)):r.onCompleted()}var e=this.parent.start,n=this.parent.rangeCount,r=this.observer;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}();We.range=function(t,e,n){return me(n)||(n=_e),new cn(t,e,n)};var hn=function(t){function e(e,n,r){this.value=e,this.repeatCount=null==n?-1:n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new V(t,this);return e.run()},e}(ze);V.prototype.run=function(){function t(t,r){return(-1===t||t>0)&&(e.onNext(n),t>0&&t--),0===t?e.onCompleted():void r(t)}var e=this.observer,n=this.parent.value;return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,t)},We.repeat=function(t,e,n){return me(n)||(n=_e),new hn(t,e,n)};var fn=function(t){function e(e,n){this.value=e,this.scheduler=n,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){var n=e[0],r=e[1];r.onNext(n),r.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState([this.parent.value,this.observer],r)},e}(ze),ln=(We["return"]=We.just=We.returnValue=function(t,e){return me(e)||(e=xe),new fn(t,e)},function(t){function e(e,n){this.error=e,this.scheduler=n,t.call(this)}function n(t,e){this.o=t,this.p=e}function r(t,e){var n=e[0],r=e[1];r.onError(n)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],r)},e}(ze)),dn=We["throw"]=We.throwError=We.throwException=function(t,e){return me(e)||(e=xe),new ln(t,e)};We.using=function(t,e){return new qn(function(n){var r,o,i=ce;try{r=t(),r&&(i=r),o=e(r)}catch(s){return new ie(dn(s).subscribe(n),i)}return new ie(o.subscribe(n),i)})},qe.amb=function(t){var e=this;return new qn(function(n){function r(){i||(i=s,c.dispose())}function o(){i||(i=u,a.dispose())}var i,s="L",u="R",a=new fe,c=new fe;return ut(t)&&(t=Xe(t)),a.setDisposable(e.subscribe(function(t){r(),i===s&&n.onNext(t)},function(t){r(),i===s&&n.onError(t)},function(){r(),i===s&&n.onCompleted()})),c.setDisposable(t.subscribe(function(t){o(),i===u&&n.onNext(t)},function(t){o(),i===u&&n.onError(t)},function(){o(),i===u&&n.onCompleted()})),new ie(a,c)})},We.amb=function(){function t(t,e){return t.amb(e)}var e=un(),n=[];if(Array.isArray(arguments[0]))n=arguments[0];else for(var r=0,o=arguments.length;o>r;r++)n.push(arguments[r]);for(var r=0,o=n.length;o>r;r++)e=t(e,n[r]);return e},qe["catch"]=qe.catchError=qe.catchException=function(t){return"function"==typeof t?$(this,t):vn([this,t])};var vn=We.catchError=We["catch"]=We.catchException=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 Ue(t).catchError()};qe.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return Array.isArray(e[0])?e[0].unshift(this):e.unshift(this),yn.apply(this,e)};var yn=We.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.pop();return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){function n(e){if(u[e]=!0,a||(a=u.every(nt))){try{var n=r.apply(null,p)}catch(o){return t.onError(o)}t.onNext(n)}else c.filter(function(t,n){return n!==e}).every(nt)&&t.onCompleted()}function o(e){c[e]=!0,c.every(nt)&&t.onCompleted()}for(var i=e.length,s=function(){return!1},u=g(i,s),a=!1,c=g(i,s),p=new Array(i),h=new Array(i),f=0;i>f;f++)!function(r){var i=e[r],s=new fe;ut(i)&&(i=Xe(i)),s.setDisposable(i.subscribe(function(t){p[r]=t,n(r)},function(e){t.onError(e)},function(){o(r)})),h[r]=s}(f);return new ie(h)},this)};qe.concat=function(){for(var t=[],e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return t.unshift(this),mn.apply(null,t)};var bn=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e){this.sources=t,this.o=e}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(this.sources,t);return e.run()},n.prototype.run=function(){var t,e=new le,n=this.sources,r=n.length,o=this.o,i=xe.scheduleRecursiveWithState(0,function(i,s){if(!t){if(i===r)return o.onCompleted();var u=n[i];ut(u)&&(u=Xe(u));var a=new fe;e.setDisposable(a),a.setDisposable(u.subscribe(function(t){o.onNext(t)},function(t){o.onError(t)},function(){s(i+1)}))}});return new ie(e,i,ae(function(){t=!0}))},e}(ze),mn=We.concat=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{t=new Array(arguments.length);for(var e=0,n=arguments.length;n>e;e++)t[e]=arguments[e]}return new bn(t)};qe.concatAll=qe.concatObservable=function(){return this.merge(1)};var gn=function(t){function e(e,n){this.source=e,this.maxConcurrent=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie;return e.add(this.source.subscribe(new wn(t,this.maxConcurrent,e))),e},e}(ze),wn=function(){function t(t,e,n){this.o=t,this.max=e,this.g=n,this.done=!1,this.q=[],this.activeCount=0,this.isStopped=!1}function e(t,e){this.parent=t,this.sad=e,this.isStopped=!1}return t.prototype.handleSubscribe=function(t){var n=new fe;this.g.add(n),ut(t)&&(t=Xe(t)),n.setDisposable(t.subscribe(new e(this,n)))},t.prototype.onNext=function(t){this.isStopped||(this.activeCount<this.max?(this.activeCount++,this.handleSubscribe(t)):this.q.push(t))},t.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},t.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,0===this.activeCount&&this.o.onCompleted())},t.prototype.dispose=function(){this.isStopped=!0},t.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},e.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=this.parent;t.g.remove(this.sad),t.q.length>0?t.handleSubscribe(t.q.shift()):(t.activeCount--,t.done&&0===t.activeCount&&t.o.onCompleted())}},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},t}();qe.merge=function(t){return"number"!=typeof t?xn(this,t):new gn(this,t)};var xn=We.merge=function(){var t,e,n=[],r=arguments.length;if(arguments[0])if(me(arguments[0]))for(t=arguments[0],e=1;r>e;e++)n.push(arguments[e]);else for(t=xe,e=0;r>e;e++)n.push(arguments[e]);else for(t=xe,e=1;r>e;e++)n.push(arguments[e]);return Array.isArray(n[0])&&(n=n[0]),M(t,n).mergeAll()},_n=tt.CompositeError=function(t){this.name="NotImplementedError",this.innerErrors=t,this.message="This contains multiple errors. Check the innerErrors",Error.call(this)};_n.prototype=Error.prototype,We.mergeDelayError=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]}var r=M(null,t);return new qn(function(t){function e(){0===s.length?t.onCompleted():1===s.length?t.onError(s[0]):t.onError(new _n(s))}var n=new ie,o=new fe,i=!1,s=[];return n.add(o),o.setDisposable(r.subscribe(function(r){var o=new fe;n.add(o),ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(e){t.onNext(e)},function(t){s.push(t),n.remove(o),i&&1===n.length&&e()},function(){n.remove(o),i&&1===n.length&&e()}))},function(t){s.push(t),i=!0,1===n.length&&e()},function(){i=!0,1===n.length&&e()})),n})};var Sn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.g=e,this.isStopped=!1,this.done=!1}function r(t,e,n){this.parent=t,this.g=e,this.sad=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie,r=new fe;return e.add(r),r.setDisposable(this.source.subscribe(new n(t,e))),e},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe;this.g.add(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,this.g,e)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,1===this.g.length&&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)},r.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},r.prototype.onCompleted=function(){if(!this.isStopped){var t=this.parent;this.isStopped=!0,t.g.remove(this.sad),t.done&&1===t.g.length&&t.o.onCompleted()}},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe.mergeAll=qe.mergeObservable=function(){
3461 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;n<t.length?(i=t[n++],ut(i)&&(i=Xe(i)),s=new fe,r.setDisposable(s),s.setDisposable(i.subscribe(e.onNext.bind(e),o,o))):e.onCompleted()});return new ie(r,o)})};qe.skipUntil=function(t){var e=this;return new qn(function(n){var r=!1,o=new ie(e.subscribe(function(t){r&&n.onNext(t)},function(t){n.onError(t)},function(){r&&n.onCompleted()}));ut(t)&&(t=Xe(t));var i=new fe;return o.add(i),i.setDisposable(t.subscribe(function(){r=!0,i.dispose()},function(t){n.onError(t)},function(){i.dispose()})),o},e)};var Cn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.inner=e,this.stopped=!1,this.latest=0,this.hasLatest=!1,this.isStopped=!1}function r(t,e){this.parent=t,this.id=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new le,r=this.source.subscribe(new n(t,e));return new ie(r,e)},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe,n=++this.latest;this.hasLatest=!0,this.inner.setDisposable(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,n)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.stopped=!0,!this.hasLatest&&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)},r.prototype.onNext=function(t){this.isStopped||this.parent.latest===this.id&&this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&this.parent.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&(this.parent.hasLatest=!1,this.parent.isStopped&&this.parent.o.onCompleted()))},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe["switch"]=qe.switchLatest=function(){return new Cn(this)};var An=function(t){function e(e,n){this.source=e,this.other=ut(n)?Xe(n):n,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return new ie(this.source.subscribe(t),this.other.subscribe(new n(t)))},n.prototype.onNext=function(t){this.isStopped||this.o.onCompleted()},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){!this.isStopped&&(this.isStopped=!0)},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.takeUntil=function(t){return new An(this,t)},qe.withLatestFrom=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;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)});
3462 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3464 },{}],16:[function(require,module,exports){
3466 var topLevel = typeof global !== 'undefined' ? global :
3467 typeof window !== 'undefined' ? window : {}
3468 var minDoc = require('min-document');
3472 if (typeof document !== 'undefined') {
3475 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3478 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3482 module.exports = doccy;
3484 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3486 },{"min-document":4}],17:[function(require,module,exports){
3487 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3489 var eLen = nBytes * 8 - mLen - 1
3490 var eMax = (1 << eLen) - 1
3491 var eBias = eMax >> 1
3493 var i = isLE ? (nBytes - 1) : 0
3494 var d = isLE ? -1 : 1
3495 var s = buffer[offset + i]
3499 e = s & ((1 << (-nBits)) - 1)
3502 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3504 m = e & ((1 << (-nBits)) - 1)
3507 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3511 } else if (e === eMax) {
3512 return m ? NaN : ((s ? -1 : 1) * Infinity)
3514 m = m + Math.pow(2, mLen)
3517 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3520 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3522 var eLen = nBytes * 8 - mLen - 1
3523 var eMax = (1 << eLen) - 1
3524 var eBias = eMax >> 1
3525 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3526 var i = isLE ? 0 : (nBytes - 1)
3527 var d = isLE ? 1 : -1
3528 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3530 value = Math.abs(value)
3532 if (isNaN(value) || value === Infinity) {
3533 m = isNaN(value) ? 1 : 0
3536 e = Math.floor(Math.log(value) / Math.LN2)
3537 if (value * (c = Math.pow(2, -e)) < 1) {
3541 if (e + eBias >= 1) {
3544 value += rt * Math.pow(2, 1 - eBias)
3546 if (value * c >= 2) {
3551 if (e + eBias >= eMax) {
3554 } else if (e + eBias >= 1) {
3555 m = (value * c - 1) * Math.pow(2, mLen)
3558 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3563 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3567 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3569 buffer[offset + i - d] |= s * 128
3572 },{}],18:[function(require,module,exports){
3576 /*global window, global*/
3578 var root = typeof window !== 'undefined' ?
3579 window : typeof global !== 'undefined' ?
3582 module.exports = Individual;
3584 function Individual(key, value) {
3594 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3596 },{}],19:[function(require,module,exports){
3599 var Individual = require('./index.js');
3601 module.exports = OneVersion;
3603 function OneVersion(moduleName, version, defaultValue) {
3604 var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3605 var enforceKey = key + '_ENFORCE_SINGLETON';
3607 var versionValue = Individual(enforceKey, version);
3609 if (versionValue !== version) {
3610 throw new Error('Can only have one copy of ' +
3611 moduleName + '.\n' +
3612 'You already have version ' + versionValue +
3614 'This means you cannot install version ' + version);
3617 return Individual(key, defaultValue);
3620 },{"./index.js":18}],20:[function(require,module,exports){
3623 module.exports = function isObject(x) {
3624 return typeof x === "object" && x !== null;
3627 },{}],21:[function(require,module,exports){
3628 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3629 /* Geohash encoding/decoding and associated functions (c) Chris Veness 2014-2016 / MIT Licence */
3630 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3636 * Geohash encode, decode, bounds, neighbours.
3642 /* (Geohash-specific) Base32 map */
3643 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3646 * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3647 * evaluated precision.
3649 * @param {number} lat - Latitude in degrees.
3650 * @param {number} lon - Longitude in degrees.
3651 * @param {number} [precision] - Number of characters in resulting geohash.
3652 * @returns {string} Geohash of supplied latitude/longitude.
3653 * @throws Invalid geohash.
3656 * var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3658 Geohash.encode = function(lat, lon, precision) {
3660 if (typeof precision == 'undefined') {
3661 // refine geohash until it matches precision of supplied lat/lon
3662 for (var p=1; p<=12; p++) {
3663 var hash = Geohash.encode(lat, lon, p);
3664 var posn = Geohash.decode(hash);
3665 if (posn.lat==lat && posn.lon==lon) return hash;
3667 precision = 12; // set to maximum
3672 precision = Number(precision);
3674 if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3676 var idx = 0; // index into base32 map
3677 var bit = 0; // each char holds 5 bits
3681 var latMin = -90, latMax = 90;
3682 var lonMin = -180, lonMax = 180;
3684 while (geohash.length < precision) {
3686 // bisect E-W longitude
3687 var lonMid = (lonMin + lonMax) / 2;
3688 if (lon >= lonMid) {
3696 // bisect N-S latitude
3697 var latMid = (latMin + latMax) / 2;
3698 if (lat >= latMid) {
3709 // 5 bits gives us a character: append it and start over
3710 geohash += Geohash.base32.charAt(idx);
3721 * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3722 * to reasonable precision).
3724 * @param {string} geohash - Geohash string to be converted to latitude/longitude.
3725 * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3726 * @throws Invalid geohash.
3729 * var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3731 Geohash.decode = function(geohash) {
3733 var bounds = Geohash.bounds(geohash); // <-- the hard work
3734 // now just determine the centre of the cell...
3736 var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3737 var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3740 var lat = (latMin + latMax)/2;
3741 var lon = (lonMin + lonMax)/2;
3743 // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3744 lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3745 lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3747 return { lat: Number(lat), lon: Number(lon) };
3752 * Returns SW/NE latitude/longitude bounds of specified geohash.
3754 * @param {string} geohash - Cell that bounds are required of.
3755 * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3756 * @throws Invalid geohash.
3758 Geohash.bounds = function(geohash) {
3759 if (geohash.length === 0) throw new Error('Invalid geohash');
3761 geohash = geohash.toLowerCase();
3764 var latMin = -90, latMax = 90;
3765 var lonMin = -180, lonMax = 180;
3767 for (var i=0; i<geohash.length; i++) {
3768 var chr = geohash.charAt(i);
3769 var idx = Geohash.base32.indexOf(chr);
3770 if (idx == -1) throw new Error('Invalid geohash');
3772 for (var n=4; n>=0; n--) {
3773 var bitN = idx >> n & 1;
3776 var lonMid = (lonMin+lonMax) / 2;
3784 var latMid = (latMin+latMax) / 2;
3796 sw: { lat: latMin, lon: lonMin },
3797 ne: { lat: latMax, lon: lonMax },
3805 * Determines adjacent cell in given direction.
3807 * @param geohash - Cell to which adjacent cell is required.
3808 * @param direction - Direction from geohash (N/S/E/W).
3809 * @returns {string} Geocode of adjacent cell.
3810 * @throws Invalid geohash.
3812 Geohash.adjacent = function(geohash, direction) {
3813 // based on github.com/davetroy/geohash-js
3815 geohash = geohash.toLowerCase();
3816 direction = direction.toLowerCase();
3818 if (geohash.length === 0) throw new Error('Invalid geohash');
3819 if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3822 n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3823 s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3824 e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3825 w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3828 n: [ 'prxz', 'bcfguvyz' ],
3829 s: [ '028b', '0145hjnp' ],
3830 e: [ 'bcfguvyz', 'prxz' ],
3831 w: [ '0145hjnp', '028b' ],
3834 var lastCh = geohash.slice(-1); // last character of hash
3835 var parent = geohash.slice(0, -1); // hash without last character
3837 var type = geohash.length % 2;
3839 // check for edge-cases which don't share common prefix
3840 if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3841 parent = Geohash.adjacent(parent, direction);
3844 // append letter for direction to parent
3845 return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3850 * Returns all 8 adjacent cells to specified geohash.
3852 * @param {string} geohash - Geohash neighbours are required of.
3853 * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3854 * @throws Invalid geohash.
3856 Geohash.neighbours = function(geohash) {
3858 'n': Geohash.adjacent(geohash, 'n'),
3859 'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3860 'e': Geohash.adjacent(geohash, 'e'),
3861 'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3862 's': Geohash.adjacent(geohash, 's'),
3863 'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3864 'w': Geohash.adjacent(geohash, 'w'),
3865 'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3870 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3871 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3873 },{}],22:[function(require,module,exports){
3874 (function (process){
3875 // Copyright Joyent, Inc. and other Node contributors.
3877 // Permission is hereby granted, free of charge, to any person obtaining a
3878 // copy of this software and associated documentation files (the
3879 // "Software"), to deal in the Software without restriction, including
3880 // without limitation the rights to use, copy, modify, merge, publish,
3881 // distribute, sublicense, and/or sell copies of the Software, and to permit
3882 // persons to whom the Software is furnished to do so, subject to the
3883 // following conditions:
3885 // The above copyright notice and this permission notice shall be included
3886 // in all copies or substantial portions of the Software.
3888 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3889 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3890 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3891 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3892 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3893 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3894 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3896 // resolves . and .. elements in a path array with directory names there
3897 // must be no slashes, empty elements, or device names (c:\) in the array
3898 // (so also no leading and trailing slashes - it does not distinguish
3899 // relative and absolute paths)
3900 function normalizeArray(parts, allowAboveRoot) {
3901 // if the path tries to go above the root, `up` ends up > 0
3903 for (var i = parts.length - 1; i >= 0; i--) {
3904 var last = parts[i];
3907 } else if (last === '..') {
3916 // if the path is allowed to go above the root, restore leading ..s
3917 if (allowAboveRoot) {
3919 parts.unshift('..');
3926 // Split a filename into [root, dir, basename, ext], unix version
3927 // 'root' is just a slash, or nothing.
3929 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3930 var splitPath = function(filename) {
3931 return splitPathRe.exec(filename).slice(1);
3934 // path.resolve([from ...], to)
3936 exports.resolve = function() {
3937 var resolvedPath = '',
3938 resolvedAbsolute = false;
3940 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3941 var path = (i >= 0) ? arguments[i] : process.cwd();
3943 // Skip empty and invalid entries
3944 if (typeof path !== 'string') {
3945 throw new TypeError('Arguments to path.resolve must be strings');
3950 resolvedPath = path + '/' + resolvedPath;
3951 resolvedAbsolute = path.charAt(0) === '/';
3954 // At this point the path should be resolved to a full absolute path, but
3955 // handle relative paths to be safe (might happen when process.cwd() fails)
3957 // Normalize the path
3958 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3960 }), !resolvedAbsolute).join('/');
3962 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3965 // path.normalize(path)
3967 exports.normalize = function(path) {
3968 var isAbsolute = exports.isAbsolute(path),
3969 trailingSlash = substr(path, -1) === '/';
3971 // Normalize the path
3972 path = normalizeArray(filter(path.split('/'), function(p) {
3974 }), !isAbsolute).join('/');
3976 if (!path && !isAbsolute) {
3979 if (path && trailingSlash) {
3983 return (isAbsolute ? '/' : '') + path;
3987 exports.isAbsolute = function(path) {
3988 return path.charAt(0) === '/';
3992 exports.join = function() {
3993 var paths = Array.prototype.slice.call(arguments, 0);
3994 return exports.normalize(filter(paths, function(p, index) {
3995 if (typeof p !== 'string') {
3996 throw new TypeError('Arguments to path.join must be strings');
4003 // path.relative(from, to)
4005 exports.relative = function(from, to) {
4006 from = exports.resolve(from).substr(1);
4007 to = exports.resolve(to).substr(1);
4009 function trim(arr) {
4011 for (; start < arr.length; start++) {
4012 if (arr[start] !== '') break;
4015 var end = arr.length - 1;
4016 for (; end >= 0; end--) {
4017 if (arr[end] !== '') break;
4020 if (start > end) return [];
4021 return arr.slice(start, end - start + 1);
4024 var fromParts = trim(from.split('/'));
4025 var toParts = trim(to.split('/'));
4027 var length = Math.min(fromParts.length, toParts.length);
4028 var samePartsLength = length;
4029 for (var i = 0; i < length; i++) {
4030 if (fromParts[i] !== toParts[i]) {
4031 samePartsLength = i;
4036 var outputParts = [];
4037 for (var i = samePartsLength; i < fromParts.length; i++) {
4038 outputParts.push('..');
4041 outputParts = outputParts.concat(toParts.slice(samePartsLength));
4043 return outputParts.join('/');
4047 exports.delimiter = ':';
4049 exports.dirname = function(path) {
4050 var result = splitPath(path),
4054 if (!root && !dir) {
4055 // No dirname whatsoever
4060 // It has a dirname, strip trailing slash
4061 dir = dir.substr(0, dir.length - 1);
4068 exports.basename = function(path, ext) {
4069 var f = splitPath(path)[2];
4070 // TODO: make this comparison case-insensitive on windows?
4071 if (ext && f.substr(-1 * ext.length) === ext) {
4072 f = f.substr(0, f.length - ext.length);
4078 exports.extname = function(path) {
4079 return splitPath(path)[3];
4082 function filter (xs, f) {
4083 if (xs.filter) return xs.filter(f);
4085 for (var i = 0; i < xs.length; i++) {
4086 if (f(xs[i], i, xs)) res.push(xs[i]);
4091 // String.prototype.substr - negative index don't work in IE8
4092 var substr = 'ab'.substr(-1) === 'b'
4093 ? function (str, start, len) { return str.substr(start, len) }
4094 : function (str, start, len) {
4095 if (start < 0) start = str.length + start;
4096 return str.substr(start, len);
4100 }).call(this,require('_process'))
4102 },{"_process":6}],23:[function(require,module,exports){
4105 module.exports = Pbf;
4107 var ieee754 = require('ieee754');
4110 this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
4113 this.length = this.buf.length;
4116 Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
4117 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
4118 Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
4119 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
4121 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
4122 SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
4126 destroy: function() {
4130 // === READING =================================================================
4132 readFields: function(readField, result, end) {
4133 end = end || this.length;
4135 while (this.pos < end) {
4136 var val = this.readVarint(),
4138 startPos = this.pos;
4140 this.type = val & 0x7;
4141 readField(tag, result, this);
4143 if (this.pos === startPos) this.skip(val);
4148 readMessage: function(readField, result) {
4149 return this.readFields(readField, result, this.readVarint() + this.pos);
4152 readFixed32: function() {
4153 var val = readUInt32(this.buf, this.pos);
4158 readSFixed32: function() {
4159 var val = readInt32(this.buf, this.pos);
4164 // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
4166 readFixed64: function() {
4167 var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4172 readSFixed64: function() {
4173 var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4178 readFloat: function() {
4179 var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4184 readDouble: function() {
4185 var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4190 readVarint: function(isSigned) {
4194 b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val;
4195 b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;
4196 b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4197 b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4198 b = buf[this.pos]; val |= (b & 0x0f) << 28;
4200 return readVarintRemainder(val, isSigned, this);
4203 readVarint64: function() { // for compatibility with v2.0.1
4204 return this.readVarint(true);
4207 readSVarint: function() {
4208 var num = this.readVarint();
4209 return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4212 readBoolean: function() {
4213 return Boolean(this.readVarint());
4216 readString: function() {
4217 var end = this.readVarint() + this.pos,
4218 str = readUtf8(this.buf, this.pos, end);
4223 readBytes: function() {
4224 var end = this.readVarint() + this.pos,
4225 buffer = this.buf.subarray(this.pos, end);
4230 // verbose for performance reasons; doesn't affect gzipped size
4232 readPackedVarint: function(arr, isSigned) {
4233 var end = readPackedEnd(this);
4235 while (this.pos < end) arr.push(this.readVarint(isSigned));
4238 readPackedSVarint: function(arr) {
4239 var end = readPackedEnd(this);
4241 while (this.pos < end) arr.push(this.readSVarint());
4244 readPackedBoolean: function(arr) {
4245 var end = readPackedEnd(this);
4247 while (this.pos < end) arr.push(this.readBoolean());
4250 readPackedFloat: function(arr) {
4251 var end = readPackedEnd(this);
4253 while (this.pos < end) arr.push(this.readFloat());
4256 readPackedDouble: function(arr) {
4257 var end = readPackedEnd(this);
4259 while (this.pos < end) arr.push(this.readDouble());
4262 readPackedFixed32: function(arr) {
4263 var end = readPackedEnd(this);
4265 while (this.pos < end) arr.push(this.readFixed32());
4268 readPackedSFixed32: function(arr) {
4269 var end = readPackedEnd(this);
4271 while (this.pos < end) arr.push(this.readSFixed32());
4274 readPackedFixed64: function(arr) {
4275 var end = readPackedEnd(this);
4277 while (this.pos < end) arr.push(this.readFixed64());
4280 readPackedSFixed64: function(arr) {
4281 var end = readPackedEnd(this);
4283 while (this.pos < end) arr.push(this.readSFixed64());
4287 skip: function(val) {
4288 var type = val & 0x7;
4289 if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4290 else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4291 else if (type === Pbf.Fixed32) this.pos += 4;
4292 else if (type === Pbf.Fixed64) this.pos += 8;
4293 else throw new Error('Unimplemented type: ' + type);
4296 // === WRITING =================================================================
4298 writeTag: function(tag, type) {
4299 this.writeVarint((tag << 3) | type);
4302 realloc: function(min) {
4303 var length = this.length || 16;
4305 while (length < this.pos + min) length *= 2;
4307 if (length !== this.length) {
4308 var buf = new Uint8Array(length);
4311 this.length = length;
4315 finish: function() {
4316 this.length = this.pos;
4318 return this.buf.subarray(0, this.length);
4321 writeFixed32: function(val) {
4323 writeInt32(this.buf, val, this.pos);
4327 writeSFixed32: function(val) {
4329 writeInt32(this.buf, val, this.pos);
4333 writeFixed64: function(val) {
4335 writeInt32(this.buf, val & -1, this.pos);
4336 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4340 writeSFixed64: function(val) {
4342 writeInt32(this.buf, val & -1, this.pos);
4343 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4347 writeVarint: function(val) {
4350 if (val > 0xfffffff || val < 0) {
4351 writeBigVarint(val, this);
4357 this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4358 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4359 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4360 this.buf[this.pos++] = (val >>> 7) & 0x7f;
4363 writeSVarint: function(val) {
4364 this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4367 writeBoolean: function(val) {
4368 this.writeVarint(Boolean(val));
4371 writeString: function(str) {
4373 this.realloc(str.length * 4);
4375 this.pos++; // reserve 1 byte for short string length
4377 var startPos = this.pos;
4378 // write the string directly to the buffer and see how much was written
4379 this.pos = writeUtf8(this.buf, str, this.pos);
4380 var len = this.pos - startPos;
4382 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4384 // finally, write the message length in the reserved place and restore the position
4385 this.pos = startPos - 1;
4386 this.writeVarint(len);
4390 writeFloat: function(val) {
4392 ieee754.write(this.buf, val, this.pos, true, 23, 4);
4396 writeDouble: function(val) {
4398 ieee754.write(this.buf, val, this.pos, true, 52, 8);
4402 writeBytes: function(buffer) {
4403 var len = buffer.length;
4404 this.writeVarint(len);
4406 for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4409 writeRawMessage: function(fn, obj) {
4410 this.pos++; // reserve 1 byte for short message length
4412 // write the message directly to the buffer and see how much was written
4413 var startPos = this.pos;
4415 var len = this.pos - startPos;
4417 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4419 // finally, write the message length in the reserved place and restore the position
4420 this.pos = startPos - 1;
4421 this.writeVarint(len);
4425 writeMessage: function(tag, fn, obj) {
4426 this.writeTag(tag, Pbf.Bytes);
4427 this.writeRawMessage(fn, obj);
4430 writePackedVarint: function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr); },
4431 writePackedSVarint: function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr); },
4432 writePackedBoolean: function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr); },
4433 writePackedFloat: function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr); },
4434 writePackedDouble: function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr); },
4435 writePackedFixed32: function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr); },
4436 writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4437 writePackedFixed64: function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr); },
4438 writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4440 writeBytesField: function(tag, buffer) {
4441 this.writeTag(tag, Pbf.Bytes);
4442 this.writeBytes(buffer);
4444 writeFixed32Field: function(tag, val) {
4445 this.writeTag(tag, Pbf.Fixed32);
4446 this.writeFixed32(val);
4448 writeSFixed32Field: function(tag, val) {
4449 this.writeTag(tag, Pbf.Fixed32);
4450 this.writeSFixed32(val);
4452 writeFixed64Field: function(tag, val) {
4453 this.writeTag(tag, Pbf.Fixed64);
4454 this.writeFixed64(val);
4456 writeSFixed64Field: function(tag, val) {
4457 this.writeTag(tag, Pbf.Fixed64);
4458 this.writeSFixed64(val);
4460 writeVarintField: function(tag, val) {
4461 this.writeTag(tag, Pbf.Varint);
4462 this.writeVarint(val);
4464 writeSVarintField: function(tag, val) {
4465 this.writeTag(tag, Pbf.Varint);
4466 this.writeSVarint(val);
4468 writeStringField: function(tag, str) {
4469 this.writeTag(tag, Pbf.Bytes);
4470 this.writeString(str);
4472 writeFloatField: function(tag, val) {
4473 this.writeTag(tag, Pbf.Fixed32);
4474 this.writeFloat(val);
4476 writeDoubleField: function(tag, val) {
4477 this.writeTag(tag, Pbf.Fixed64);
4478 this.writeDouble(val);
4480 writeBooleanField: function(tag, val) {
4481 this.writeVarintField(tag, Boolean(val));
4485 function readVarintRemainder(l, s, p) {
4489 b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);
4490 b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);
4491 b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4492 b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4493 b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4494 b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4496 throw new Error('Expected varint not more than 10 bytes');
4499 function readPackedEnd(pbf) {
4500 return pbf.type === Pbf.Bytes ?
4501 pbf.readVarint() + pbf.pos : pbf.pos + 1;
4504 function toNum(low, high, isSigned) {
4506 return high * 0x100000000 + (low >>> 0);
4509 return ((high >>> 0) * 0x100000000) + (low >>> 0);
4512 function writeBigVarint(val, pbf) {
4516 low = (val % 0x100000000) | 0;
4517 high = (val / 0x100000000) | 0;
4519 low = ~(-val % 0x100000000);
4520 high = ~(-val / 0x100000000);
4522 if (low ^ 0xffffffff) {
4523 low = (low + 1) | 0;
4526 high = (high + 1) | 0;
4530 if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4531 throw new Error('Given varint doesn\'t fit into 10 bytes');
4536 writeBigVarintLow(low, high, pbf);
4537 writeBigVarintHigh(high, pbf);
4540 function writeBigVarintLow(low, high, pbf) {
4541 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4542 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4543 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4544 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4545 pbf.buf[pbf.pos] = low & 0x7f;
4548 function writeBigVarintHigh(high, pbf) {
4549 var lsb = (high & 0x07) << 4;
4551 pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4552 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4553 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4554 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4555 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4556 pbf.buf[pbf.pos++] = high & 0x7f;
4559 function makeRoomForExtraLength(startPos, len, pbf) {
4562 len <= 0x1fffff ? 2 :
4563 len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4565 // if 1 byte isn't enough for encoding message length, shift the data to the right
4566 pbf.realloc(extraLen);
4567 for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4570 function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); }
4571 function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); }
4572 function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); }
4573 function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); }
4574 function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); }
4575 function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); }
4576 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4577 function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); }
4578 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4580 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4582 function readUInt32(buf, pos) {
4583 return ((buf[pos]) |
4584 (buf[pos + 1] << 8) |
4585 (buf[pos + 2] << 16)) +
4586 (buf[pos + 3] * 0x1000000);
4589 function writeInt32(buf, val, pos) {
4591 buf[pos + 1] = (val >>> 8);
4592 buf[pos + 2] = (val >>> 16);
4593 buf[pos + 3] = (val >>> 24);
4596 function readInt32(buf, pos) {
4597 return ((buf[pos]) |
4598 (buf[pos + 1] << 8) |
4599 (buf[pos + 2] << 16)) +
4600 (buf[pos + 3] << 24);
4603 function readUtf8(buf, pos, end) {
4609 var c = null; // codepoint
4610 var bytesPerSequence =
4615 if (i + bytesPerSequence > end) break;
4619 if (bytesPerSequence === 1) {
4623 } else if (bytesPerSequence === 2) {
4625 if ((b1 & 0xC0) === 0x80) {
4626 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4631 } else if (bytesPerSequence === 3) {
4634 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4635 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4636 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4640 } else if (bytesPerSequence === 4) {
4644 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4645 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4646 if (c <= 0xFFFF || c >= 0x110000) {
4654 bytesPerSequence = 1;
4656 } else if (c > 0xFFFF) {
4658 str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4659 c = 0xDC00 | c & 0x3FF;
4662 str += String.fromCharCode(c);
4663 i += bytesPerSequence;
4669 function writeUtf8(buf, str, pos) {
4670 for (var i = 0, c, lead; i < str.length; i++) {
4671 c = str.charCodeAt(i); // code point
4673 if (c > 0xD7FF && c < 0xE000) {
4682 c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4686 if (c > 0xDBFF || (i + 1 === str.length)) {
4706 buf[pos++] = c >> 0x6 | 0xC0;
4709 buf[pos++] = c >> 0xC | 0xE0;
4711 buf[pos++] = c >> 0x12 | 0xF0;
4712 buf[pos++] = c >> 0xC & 0x3F | 0x80;
4714 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4716 buf[pos++] = c & 0x3F | 0x80;
4722 },{"ieee754":17}],24:[function(require,module,exports){
4725 module.exports = partialSort;
4727 // Floyd-Rivest selection algorithm:
4728 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4729 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4731 function partialSort(arr, k, left, right, compare) {
4733 right = right || (arr.length - 1);
4734 compare = compare || defaultCompare;
4736 while (right > left) {
4737 if (right - left > 600) {
4738 var n = right - left + 1;
4739 var m = k - left + 1;
4740 var z = Math.log(n);
4741 var s = 0.5 * Math.exp(2 * z / 3);
4742 var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4743 var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4744 var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4745 partialSort(arr, k, newLeft, newRight, compare);
4753 if (compare(arr[right], t) > 0) swap(arr, left, right);
4759 while (compare(arr[i], t) < 0) i++;
4760 while (compare(arr[j], t) > 0) j--;
4763 if (compare(arr[left], t) === 0) swap(arr, left, j);
4766 swap(arr, j, right);
4769 if (j <= k) left = j + 1;
4770 if (k <= j) right = j - 1;
4774 function swap(arr, i, j) {
4780 function defaultCompare(a, b) {
4781 return a < b ? -1 : a > b ? 1 : 0;
4784 },{}],25:[function(require,module,exports){
4787 module.exports = rbush;
4789 var quickselect = require('quickselect');
4791 function rbush(maxEntries, format) {
4792 if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4794 // max entries in a node is 9 by default; min node fill is 40% for best performance
4795 this._maxEntries = Math.max(4, maxEntries || 9);
4796 this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4799 this._initFormat(format);
4808 return this._all(this.data, []);
4811 search: function (bbox) {
4813 var node = this.data,
4815 toBBox = this.toBBox;
4817 if (!intersects(bbox, node)) return result;
4819 var nodesToSearch = [],
4820 i, len, child, childBBox;
4823 for (i = 0, len = node.children.length; i < len; i++) {
4825 child = node.children[i];
4826 childBBox = node.leaf ? toBBox(child) : child;
4828 if (intersects(bbox, childBBox)) {
4829 if (node.leaf) result.push(child);
4830 else if (contains(bbox, childBBox)) this._all(child, result);
4831 else nodesToSearch.push(child);
4834 node = nodesToSearch.pop();
4840 collides: function (bbox) {
4842 var node = this.data,
4843 toBBox = this.toBBox;
4845 if (!intersects(bbox, node)) return false;
4847 var nodesToSearch = [],
4848 i, len, child, childBBox;
4851 for (i = 0, len = node.children.length; i < len; i++) {
4853 child = node.children[i];
4854 childBBox = node.leaf ? toBBox(child) : child;
4856 if (intersects(bbox, childBBox)) {
4857 if (node.leaf || contains(bbox, childBBox)) return true;
4858 nodesToSearch.push(child);
4861 node = nodesToSearch.pop();
4867 load: function (data) {
4868 if (!(data && data.length)) return this;
4870 if (data.length < this._minEntries) {
4871 for (var i = 0, len = data.length; i < len; i++) {
4872 this.insert(data[i]);
4877 // recursively build the tree with the given data from stratch using OMT algorithm
4878 var node = this._build(data.slice(), 0, data.length - 1, 0);
4880 if (!this.data.children.length) {
4881 // save as is if tree is empty
4884 } else if (this.data.height === node.height) {
4885 // split root if trees have the same height
4886 this._splitRoot(this.data, node);
4889 if (this.data.height < node.height) {
4890 // swap trees if inserted one is bigger
4891 var tmpNode = this.data;
4896 // insert the small tree into the large tree at appropriate level
4897 this._insert(node, this.data.height - node.height - 1, true);
4903 insert: function (item) {
4904 if (item) this._insert(item, this.data.height - 1);
4908 clear: function () {
4909 this.data = createNode([]);
4913 remove: function (item, equalsFn) {
4914 if (!item) return this;
4916 var node = this.data,
4917 bbox = this.toBBox(item),
4920 i, parent, index, goingUp;
4922 // depth-first iterative tree traversal
4923 while (node || path.length) {
4925 if (!node) { // go up
4927 parent = path[path.length - 1];
4932 if (node.leaf) { // check current node
4933 index = findItem(item, node.children, equalsFn);
4936 // item found, remove the item and condense tree upwards
4937 node.children.splice(index, 1);
4939 this._condense(path);
4944 if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4949 node = node.children[0];
4951 } else if (parent) { // go right
4953 node = parent.children[i];
4956 } else node = null; // nothing found
4962 toBBox: function (item) { return item; },
4964 compareMinX: compareNodeMinX,
4965 compareMinY: compareNodeMinY,
4967 toJSON: function () { return this.data; },
4969 fromJSON: function (data) {
4974 _all: function (node, result) {
4975 var nodesToSearch = [];
4977 if (node.leaf) result.push.apply(result, node.children);
4978 else nodesToSearch.push.apply(nodesToSearch, node.children);
4980 node = nodesToSearch.pop();
4985 _build: function (items, left, right, height) {
4987 var N = right - left + 1,
4988 M = this._maxEntries,
4992 // reached leaf level; return leaf
4993 node = createNode(items.slice(left, right + 1));
4994 calcBBox(node, this.toBBox);
4999 // target height of the bulk-loaded tree
5000 height = Math.ceil(Math.log(N) / Math.log(M));
5002 // target number of root entries to maximize storage utilization
5003 M = Math.ceil(N / Math.pow(M, height - 1));
5006 node = createNode([]);
5008 node.height = height;
5010 // split the items into M mostly square tiles
5012 var N2 = Math.ceil(N / M),
5013 N1 = N2 * Math.ceil(Math.sqrt(M)),
5014 i, j, right2, right3;
5016 multiSelect(items, left, right, N1, this.compareMinX);
5018 for (i = left; i <= right; i += N1) {
5020 right2 = Math.min(i + N1 - 1, right);
5022 multiSelect(items, i, right2, N2, this.compareMinY);
5024 for (j = i; j <= right2; j += N2) {
5026 right3 = Math.min(j + N2 - 1, right2);
5028 // pack each entry recursively
5029 node.children.push(this._build(items, j, right3, height - 1));
5033 calcBBox(node, this.toBBox);
5038 _chooseSubtree: function (bbox, node, level, path) {
5040 var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
5045 if (node.leaf || path.length - 1 === level) break;
5047 minArea = minEnlargement = Infinity;
5049 for (i = 0, len = node.children.length; i < len; i++) {
5050 child = node.children[i];
5051 area = bboxArea(child);
5052 enlargement = enlargedArea(bbox, child) - area;
5054 // choose entry with the least area enlargement
5055 if (enlargement < minEnlargement) {
5056 minEnlargement = enlargement;
5057 minArea = area < minArea ? area : minArea;
5060 } else if (enlargement === minEnlargement) {
5061 // otherwise choose one with the smallest area
5062 if (area < minArea) {
5069 node = targetNode || node.children[0];
5075 _insert: function (item, level, isNode) {
5077 var toBBox = this.toBBox,
5078 bbox = isNode ? item : toBBox(item),
5081 // find the best node for accommodating the item, saving all nodes along the path too
5082 var node = this._chooseSubtree(bbox, this.data, level, insertPath);
5084 // put the item into the node
5085 node.children.push(item);
5088 // split on node overflow; propagate upwards if necessary
5089 while (level >= 0) {
5090 if (insertPath[level].children.length > this._maxEntries) {
5091 this._split(insertPath, level);
5096 // adjust bboxes along the insertion path
5097 this._adjustParentBBoxes(bbox, insertPath, level);
5100 // split overflowed node into two
5101 _split: function (insertPath, level) {
5103 var node = insertPath[level],
5104 M = node.children.length,
5105 m = this._minEntries;
5107 this._chooseSplitAxis(node, m, M);
5109 var splitIndex = this._chooseSplitIndex(node, m, M);
5111 var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
5112 newNode.height = node.height;
5113 newNode.leaf = node.leaf;
5115 calcBBox(node, this.toBBox);
5116 calcBBox(newNode, this.toBBox);
5118 if (level) insertPath[level - 1].children.push(newNode);
5119 else this._splitRoot(node, newNode);
5122 _splitRoot: function (node, newNode) {
5124 this.data = createNode([node, newNode]);
5125 this.data.height = node.height + 1;
5126 this.data.leaf = false;
5127 calcBBox(this.data, this.toBBox);
5130 _chooseSplitIndex: function (node, m, M) {
5132 var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
5134 minOverlap = minArea = Infinity;
5136 for (i = m; i <= M - m; i++) {
5137 bbox1 = distBBox(node, 0, i, this.toBBox);
5138 bbox2 = distBBox(node, i, M, this.toBBox);
5140 overlap = intersectionArea(bbox1, bbox2);
5141 area = bboxArea(bbox1) + bboxArea(bbox2);
5143 // choose distribution with minimum overlap
5144 if (overlap < minOverlap) {
5145 minOverlap = overlap;
5148 minArea = area < minArea ? area : minArea;
5150 } else if (overlap === minOverlap) {
5151 // otherwise choose distribution with minimum area
5152 if (area < minArea) {
5162 // sorts node children by the best axis for split
5163 _chooseSplitAxis: function (node, m, M) {
5165 var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
5166 compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
5167 xMargin = this._allDistMargin(node, m, M, compareMinX),
5168 yMargin = this._allDistMargin(node, m, M, compareMinY);
5170 // if total distributions margin value is minimal for x, sort by minX,
5171 // otherwise it's already sorted by minY
5172 if (xMargin < yMargin) node.children.sort(compareMinX);
5175 // total margin of all possible split distributions where each node is at least m full
5176 _allDistMargin: function (node, m, M, compare) {
5178 node.children.sort(compare);
5180 var toBBox = this.toBBox,
5181 leftBBox = distBBox(node, 0, m, toBBox),
5182 rightBBox = distBBox(node, M - m, M, toBBox),
5183 margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5186 for (i = m; i < M - m; i++) {
5187 child = node.children[i];
5188 extend(leftBBox, node.leaf ? toBBox(child) : child);
5189 margin += bboxMargin(leftBBox);
5192 for (i = M - m - 1; i >= m; i--) {
5193 child = node.children[i];
5194 extend(rightBBox, node.leaf ? toBBox(child) : child);
5195 margin += bboxMargin(rightBBox);
5201 _adjustParentBBoxes: function (bbox, path, level) {
5202 // adjust bboxes along the given tree path
5203 for (var i = level; i >= 0; i--) {
5204 extend(path[i], bbox);
5208 _condense: function (path) {
5209 // go through the path, removing empty nodes and updating bboxes
5210 for (var i = path.length - 1, siblings; i >= 0; i--) {
5211 if (path[i].children.length === 0) {
5213 siblings = path[i - 1].children;
5214 siblings.splice(siblings.indexOf(path[i]), 1);
5216 } else this.clear();
5218 } else calcBBox(path[i], this.toBBox);
5222 _initFormat: function (format) {
5223 // data format (minX, minY, maxX, maxY accessors)
5225 // uses eval-type function compilation instead of just accepting a toBBox function
5226 // because the algorithms are very sensitive to sorting functions performance,
5227 // so they should be dead simple and without inner calls
5229 var compareArr = ['return a', ' - b', ';'];
5231 this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5232 this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5234 this.toBBox = new Function('a',
5235 'return {minX: a' + format[0] +
5236 ', minY: a' + format[1] +
5237 ', maxX: a' + format[2] +
5238 ', maxY: a' + format[3] + '};');
5242 function findItem(item, items, equalsFn) {
5243 if (!equalsFn) return items.indexOf(item);
5245 for (var i = 0; i < items.length; i++) {
5246 if (equalsFn(item, items[i])) return i;
5251 // calculate node's bbox from bboxes of its children
5252 function calcBBox(node, toBBox) {
5253 distBBox(node, 0, node.children.length, toBBox, node);
5256 // min bounding rectangle of node children from k to p-1
5257 function distBBox(node, k, p, toBBox, destNode) {
5258 if (!destNode) destNode = createNode(null);
5259 destNode.minX = Infinity;
5260 destNode.minY = Infinity;
5261 destNode.maxX = -Infinity;
5262 destNode.maxY = -Infinity;
5264 for (var i = k, child; i < p; i++) {
5265 child = node.children[i];
5266 extend(destNode, node.leaf ? toBBox(child) : child);
5272 function extend(a, b) {
5273 a.minX = Math.min(a.minX, b.minX);
5274 a.minY = Math.min(a.minY, b.minY);
5275 a.maxX = Math.max(a.maxX, b.maxX);
5276 a.maxY = Math.max(a.maxY, b.maxY);
5280 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5281 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5283 function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5284 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5286 function enlargedArea(a, b) {
5287 return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5288 (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5291 function intersectionArea(a, b) {
5292 var minX = Math.max(a.minX, b.minX),
5293 minY = Math.max(a.minY, b.minY),
5294 maxX = Math.min(a.maxX, b.maxX),
5295 maxY = Math.min(a.maxY, b.maxY);
5297 return Math.max(0, maxX - minX) *
5298 Math.max(0, maxY - minY);
5301 function contains(a, b) {
5302 return a.minX <= b.minX &&
5308 function intersects(a, b) {
5309 return b.minX <= a.maxX &&
5315 function createNode(children) {
5327 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5328 // combines selection algorithm with binary divide & conquer approach
5330 function multiSelect(arr, left, right, n, compare) {
5331 var stack = [left, right],
5334 while (stack.length) {
5335 right = stack.pop();
5338 if (right - left <= n) continue;
5340 mid = left + Math.ceil((right - left) / n / 2) * n;
5341 quickselect(arr, mid, left, right, compare);
5343 stack.push(left, mid, mid, right);
5347 },{"quickselect":24}],26:[function(require,module,exports){
5349 var __extends = (this && this.__extends) || function (d, b) {
5350 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5351 function __() { this.constructor = d; }
5352 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5354 var Subject_1 = require('./Subject');
5355 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5357 * @class BehaviorSubject<T>
5359 var BehaviorSubject = (function (_super) {
5360 __extends(BehaviorSubject, _super);
5361 function BehaviorSubject(_value) {
5363 this._value = _value;
5365 Object.defineProperty(BehaviorSubject.prototype, "value", {
5367 return this.getValue();
5372 BehaviorSubject.prototype._subscribe = function (subscriber) {
5373 var subscription = _super.prototype._subscribe.call(this, subscriber);
5374 if (subscription && !subscription.closed) {
5375 subscriber.next(this._value);
5377 return subscription;
5379 BehaviorSubject.prototype.getValue = function () {
5380 if (this.hasError) {
5381 throw this.thrownError;
5383 else if (this.closed) {
5384 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5390 BehaviorSubject.prototype.next = function (value) {
5391 _super.prototype.next.call(this, this._value = value);
5393 return BehaviorSubject;
5394 }(Subject_1.Subject));
5395 exports.BehaviorSubject = BehaviorSubject;
5397 },{"./Subject":34,"./util/ObjectUnsubscribedError":211}],27:[function(require,module,exports){
5399 var __extends = (this && this.__extends) || function (d, b) {
5400 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5401 function __() { this.constructor = d; }
5402 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5404 var Subscriber_1 = require('./Subscriber');
5406 * We need this JSDoc comment for affecting ESDoc.
5408 * @extends {Ignored}
5410 var InnerSubscriber = (function (_super) {
5411 __extends(InnerSubscriber, _super);
5412 function InnerSubscriber(parent, outerValue, outerIndex) {
5414 this.parent = parent;
5415 this.outerValue = outerValue;
5416 this.outerIndex = outerIndex;
5419 InnerSubscriber.prototype._next = function (value) {
5420 this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5422 InnerSubscriber.prototype._error = function (error) {
5423 this.parent.notifyError(error, this);
5426 InnerSubscriber.prototype._complete = function () {
5427 this.parent.notifyComplete(this);
5430 return InnerSubscriber;
5431 }(Subscriber_1.Subscriber));
5432 exports.InnerSubscriber = InnerSubscriber;
5434 },{"./Subscriber":36}],28:[function(require,module,exports){
5436 var Observable_1 = require('./Observable');
5438 * Represents a push-based event or value that an {@link Observable} can emit.
5439 * This class is particularly useful for operators that manage notifications,
5440 * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5441 * others. Besides wrapping the actual delivered value, it also annotates it
5442 * with metadata of, for instance, what type of push message it is (`next`,
5443 * `error`, or `complete`).
5445 * @see {@link materialize}
5446 * @see {@link dematerialize}
5447 * @see {@link observeOn}
5449 * @class Notification<T>
5451 var Notification = (function () {
5452 function Notification(kind, value, error) {
5456 this.hasValue = kind === 'N';
5459 * Delivers to the given `observer` the value wrapped by this Notification.
5460 * @param {Observer} observer
5463 Notification.prototype.observe = function (observer) {
5464 switch (this.kind) {
5466 return observer.next && observer.next(this.value);
5468 return observer.error && observer.error(this.error);
5470 return observer.complete && observer.complete();
5474 * Given some {@link Observer} callbacks, deliver the value represented by the
5475 * current Notification to the correctly corresponding callback.
5476 * @param {function(value: T): void} next An Observer `next` callback.
5477 * @param {function(err: any): void} [error] An Observer `error` callback.
5478 * @param {function(): void} [complete] An Observer `complete` callback.
5481 Notification.prototype.do = function (next, error, complete) {
5482 var kind = this.kind;
5485 return next && next(this.value);
5487 return error && error(this.error);
5489 return complete && complete();
5493 * Takes an Observer or its individual callback functions, and calls `observe`
5494 * or `do` methods accordingly.
5495 * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5496 * the `next` callback.
5497 * @param {function(err: any): void} [error] An Observer `error` callback.
5498 * @param {function(): void} [complete] An Observer `complete` callback.
5501 Notification.prototype.accept = function (nextOrObserver, error, complete) {
5502 if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5503 return this.observe(nextOrObserver);
5506 return this.do(nextOrObserver, error, complete);
5510 * Returns a simple Observable that just delivers the notification represented
5511 * by this Notification instance.
5514 Notification.prototype.toObservable = function () {
5515 var kind = this.kind;
5518 return Observable_1.Observable.of(this.value);
5520 return Observable_1.Observable.throw(this.error);
5522 return Observable_1.Observable.empty();
5524 throw new Error('unexpected notification kind value');
5527 * A shortcut to create a Notification instance of the type `next` from a
5529 * @param {T} value The `next` value.
5530 * @return {Notification<T>} The "next" Notification representing the
5533 Notification.createNext = function (value) {
5534 if (typeof value !== 'undefined') {
5535 return new Notification('N', value);
5537 return Notification.undefinedValueNotification;
5540 * A shortcut to create a Notification instance of the type `error` from a
5542 * @param {any} [err] The `error` error.
5543 * @return {Notification<T>} The "error" Notification representing the
5546 Notification.createError = function (err) {
5547 return new Notification('E', undefined, err);
5550 * A shortcut to create a Notification instance of the type `complete`.
5551 * @return {Notification<any>} The valueless "complete" Notification.
5553 Notification.createComplete = function () {
5554 return Notification.completeNotification;
5556 Notification.completeNotification = new Notification('C');
5557 Notification.undefinedValueNotification = new Notification('N', undefined);
5558 return Notification;
5560 exports.Notification = Notification;
5562 },{"./Observable":29}],29:[function(require,module,exports){
5564 var root_1 = require('./util/root');
5565 var toSubscriber_1 = require('./util/toSubscriber');
5566 var observable_1 = require('./symbol/observable');
5567 var pipe_1 = require('./util/pipe');
5569 * A representation of any set of values over any amount of time. This is the most basic building block
5572 * @class Observable<T>
5574 var Observable = (function () {
5577 * @param {Function} subscribe the function that is called when the Observable is
5578 * initially subscribed to. This function is given a Subscriber, to which new values
5579 * can be `next`ed, or an `error` method can be called to raise an error, or
5580 * `complete` can be called to notify of a successful completion.
5582 function Observable(subscribe) {
5583 this._isScalar = false;
5585 this._subscribe = subscribe;
5589 * Creates a new Observable, with this Observable as the source, and the passed
5590 * operator defined as the new observable's operator.
5592 * @param {Operator} operator the operator defining the operation to take on the observable
5593 * @return {Observable} a new observable with the Operator applied
5595 Observable.prototype.lift = function (operator) {
5596 var observable = new Observable();
5597 observable.source = this;
5598 observable.operator = operator;
5602 * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
5604 * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
5606 * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
5607 * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
5608 * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
5609 * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
5612 * Apart from starting the execution of an Observable, this method allows you to listen for values
5613 * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
5616 * The first way is creating an object that implements {@link Observer} interface. It should have methods
5617 * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
5618 * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
5619 * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
5620 * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
5621 * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
5624 * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
5625 * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
5626 * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
5627 * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
5628 * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
5629 * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
5631 * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
5632 * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
5633 * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
5634 * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
5636 * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
5637 * It is an Observable itself that decides when these functions will be called. For example {@link of}
5638 * by default emits all its values synchronously. Always check documentation for how given Observable
5639 * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
5641 * @example <caption>Subscribe with an Observer</caption>
5642 * const sumObserver = {
5645 * console.log('Adding: ' + value);
5646 * this.sum = this.sum + value;
5648 * error() { // We actually could just remove this method,
5649 * }, // since we do not really care about errors right now.
5651 * console.log('Sum equals: ' + this.sum);
5655 * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
5656 * .subscribe(sumObserver);
5662 * // "Sum equals: 6"
5665 * @example <caption>Subscribe with functions</caption>
5668 * Rx.Observable.of(1, 2, 3)
5671 * console.log('Adding: ' + value);
5672 * sum = sum + value;
5676 * console.log('Sum equals: ' + sum);
5684 * // "Sum equals: 6"
5687 * @example <caption>Cancel a subscription</caption>
5688 * const subscription = Rx.Observable.interval(1000).subscribe(
5689 * num => console.log(num),
5691 * () => console.log('completed!') // Will not be called, even
5692 * ); // when cancelling subscription
5695 * setTimeout(() => {
5696 * subscription.unsubscribe();
5697 * console.log('unsubscribed!');
5703 * // "unsubscribed!" after 2.5s
5706 * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
5707 * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
5709 * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
5710 * the error will be thrown as unhandled.
5711 * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
5712 * @return {ISubscription} a subscription reference to the registered handlers
5715 Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5716 var operator = this.operator;
5717 var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5719 operator.call(sink, this.source);
5722 sink.add(this.source ? this._subscribe(sink) : this._trySubscribe(sink));
5724 if (sink.syncErrorThrowable) {
5725 sink.syncErrorThrowable = false;
5726 if (sink.syncErrorThrown) {
5727 throw sink.syncErrorValue;
5732 Observable.prototype._trySubscribe = function (sink) {
5734 return this._subscribe(sink);
5737 sink.syncErrorThrown = true;
5738 sink.syncErrorValue = err;
5744 * @param {Function} next a handler for each value emitted by the observable
5745 * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5746 * @return {Promise} a promise that either resolves on observable completion or
5747 * rejects with the handled error
5749 Observable.prototype.forEach = function (next, PromiseCtor) {
5752 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5753 PromiseCtor = root_1.root.Rx.config.Promise;
5755 else if (root_1.root.Promise) {
5756 PromiseCtor = root_1.root.Promise;
5760 throw new Error('no Promise impl found');
5762 return new PromiseCtor(function (resolve, reject) {
5763 // Must be declared in a separate statement to avoid a RefernceError when
5764 // accessing subscription below in the closure due to Temporal Dead Zone.
5766 subscription = _this.subscribe(function (value) {
5768 // if there is a subscription, then we can surmise
5769 // the next handling is asynchronous. Any errors thrown
5770 // need to be rejected explicitly and unsubscribe must be
5777 subscription.unsubscribe();
5781 // if there is NO subscription, then we're getting a nexted
5782 // value synchronously during subscription. We can just call it.
5783 // If it errors, Observable's `subscribe` will ensure the
5784 // unsubscription logic is called, then synchronously rethrow the error.
5785 // After that, Promise will trap the error and send it
5786 // down the rejection path.
5789 }, reject, resolve);
5792 Observable.prototype._subscribe = function (subscriber) {
5793 return this.source.subscribe(subscriber);
5796 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5797 * @method Symbol.observable
5798 * @return {Observable} this instance of the observable
5800 Observable.prototype[observable_1.observable] = function () {
5803 /* tslint:enable:max-line-length */
5805 * Used to stitch together functional operators into a chain.
5807 * @return {Observable} the Observable result of all of the operators having
5808 * been called in the order they were passed in.
5812 * import { map, filter, scan } from 'rxjs/operators';
5814 * Rx.Observable.interval(1000)
5816 * filter(x => x % 2 === 0),
5818 * scan((acc, x) => acc + x)
5820 * .subscribe(x => console.log(x))
5822 Observable.prototype.pipe = function () {
5823 var operations = [];
5824 for (var _i = 0; _i < arguments.length; _i++) {
5825 operations[_i - 0] = arguments[_i];
5827 if (operations.length === 0) {
5830 return pipe_1.pipeFromArray(operations)(this);
5832 /* tslint:enable:max-line-length */
5833 Observable.prototype.toPromise = function (PromiseCtor) {
5836 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5837 PromiseCtor = root_1.root.Rx.config.Promise;
5839 else if (root_1.root.Promise) {
5840 PromiseCtor = root_1.root.Promise;
5844 throw new Error('no Promise impl found');
5846 return new PromiseCtor(function (resolve, reject) {
5848 _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
5851 // HACK: Since TypeScript inherits static properties too, we have to
5852 // fight against TypeScript here so Subject can have a different static create signature
5854 * Creates a new cold Observable by calling the Observable constructor
5858 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5859 * @return {Observable} a new cold observable
5861 Observable.create = function (subscribe) {
5862 return new Observable(subscribe);
5866 exports.Observable = Observable;
5868 },{"./symbol/observable":206,"./util/pipe":226,"./util/root":227,"./util/toSubscriber":229}],30:[function(require,module,exports){
5872 next: function (value) { },
5873 error: function (err) { throw err; },
5874 complete: function () { }
5877 },{}],31:[function(require,module,exports){
5879 var __extends = (this && this.__extends) || function (d, b) {
5880 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5881 function __() { this.constructor = d; }
5882 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5884 var Subscriber_1 = require('./Subscriber');
5886 * We need this JSDoc comment for affecting ESDoc.
5888 * @extends {Ignored}
5890 var OuterSubscriber = (function (_super) {
5891 __extends(OuterSubscriber, _super);
5892 function OuterSubscriber() {
5893 _super.apply(this, arguments);
5895 OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5896 this.destination.next(innerValue);
5898 OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5899 this.destination.error(error);
5901 OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5902 this.destination.complete();
5904 return OuterSubscriber;
5905 }(Subscriber_1.Subscriber));
5906 exports.OuterSubscriber = OuterSubscriber;
5908 },{"./Subscriber":36}],32:[function(require,module,exports){
5910 var __extends = (this && this.__extends) || function (d, b) {
5911 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5912 function __() { this.constructor = d; }
5913 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5915 var Subject_1 = require('./Subject');
5916 var queue_1 = require('./scheduler/queue');
5917 var Subscription_1 = require('./Subscription');
5918 var observeOn_1 = require('./operators/observeOn');
5919 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5920 var SubjectSubscription_1 = require('./SubjectSubscription');
5922 * @class ReplaySubject<T>
5924 var ReplaySubject = (function (_super) {
5925 __extends(ReplaySubject, _super);
5926 function ReplaySubject(bufferSize, windowTime, scheduler) {
5927 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5928 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5930 this.scheduler = scheduler;
5932 this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5933 this._windowTime = windowTime < 1 ? 1 : windowTime;
5935 ReplaySubject.prototype.next = function (value) {
5936 var now = this._getNow();
5937 this._events.push(new ReplayEvent(now, value));
5938 this._trimBufferThenGetEvents();
5939 _super.prototype.next.call(this, value);
5941 ReplaySubject.prototype._subscribe = function (subscriber) {
5942 var _events = this._trimBufferThenGetEvents();
5943 var scheduler = this.scheduler;
5946 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5948 else if (this.hasError) {
5949 subscription = Subscription_1.Subscription.EMPTY;
5951 else if (this.isStopped) {
5952 subscription = Subscription_1.Subscription.EMPTY;
5955 this.observers.push(subscriber);
5956 subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5959 subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5961 var len = _events.length;
5962 for (var i = 0; i < len && !subscriber.closed; i++) {
5963 subscriber.next(_events[i].value);
5965 if (this.hasError) {
5966 subscriber.error(this.thrownError);
5968 else if (this.isStopped) {
5969 subscriber.complete();
5971 return subscription;
5973 ReplaySubject.prototype._getNow = function () {
5974 return (this.scheduler || queue_1.queue).now();
5976 ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5977 var now = this._getNow();
5978 var _bufferSize = this._bufferSize;
5979 var _windowTime = this._windowTime;
5980 var _events = this._events;
5981 var eventsCount = _events.length;
5982 var spliceCount = 0;
5983 // Trim events that fall out of the time window.
5984 // Start at the front of the list. Break early once
5985 // we encounter an event that falls within the window.
5986 while (spliceCount < eventsCount) {
5987 if ((now - _events[spliceCount].time) < _windowTime) {
5992 if (eventsCount > _bufferSize) {
5993 spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5995 if (spliceCount > 0) {
5996 _events.splice(0, spliceCount);
6000 return ReplaySubject;
6001 }(Subject_1.Subject));
6002 exports.ReplaySubject = ReplaySubject;
6003 var ReplayEvent = (function () {
6004 function ReplayEvent(time, value) {
6011 },{"./Subject":34,"./SubjectSubscription":35,"./Subscription":37,"./operators/observeOn":174,"./scheduler/queue":204,"./util/ObjectUnsubscribedError":211}],33:[function(require,module,exports){
6014 * An execution context and a data structure to order tasks and schedule their
6015 * execution. Provides a notion of (potentially virtual) time, through the
6016 * `now()` getter method.
6018 * Each unit of work in a Scheduler is called an {@link Action}.
6023 * schedule(work, delay?, state?): Subscription;
6029 var Scheduler = (function () {
6030 function Scheduler(SchedulerAction, now) {
6031 if (now === void 0) { now = Scheduler.now; }
6032 this.SchedulerAction = SchedulerAction;
6036 * Schedules a function, `work`, for execution. May happen at some point in
6037 * the future, according to the `delay` parameter, if specified. May be passed
6038 * some context object, `state`, which will be passed to the `work` function.
6040 * The given arguments will be processed an stored as an Action object in a
6043 * @param {function(state: ?T): ?Subscription} work A function representing a
6044 * task, or some unit of work to be executed by the Scheduler.
6045 * @param {number} [delay] Time to wait before executing the work, where the
6046 * time unit is implicit and defined by the Scheduler itself.
6047 * @param {T} [state] Some contextual data that the `work` function uses when
6048 * called by the Scheduler.
6049 * @return {Subscription} A subscription in order to be able to unsubscribe
6050 * the scheduled work.
6052 Scheduler.prototype.schedule = function (work, delay, state) {
6053 if (delay === void 0) { delay = 0; }
6054 return new this.SchedulerAction(this, work).schedule(state, delay);
6056 Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
6059 exports.Scheduler = Scheduler;
6061 },{}],34:[function(require,module,exports){
6063 var __extends = (this && this.__extends) || function (d, b) {
6064 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6065 function __() { this.constructor = d; }
6066 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6068 var Observable_1 = require('./Observable');
6069 var Subscriber_1 = require('./Subscriber');
6070 var Subscription_1 = require('./Subscription');
6071 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
6072 var SubjectSubscription_1 = require('./SubjectSubscription');
6073 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6075 * @class SubjectSubscriber<T>
6077 var SubjectSubscriber = (function (_super) {
6078 __extends(SubjectSubscriber, _super);
6079 function SubjectSubscriber(destination) {
6080 _super.call(this, destination);
6081 this.destination = destination;
6083 return SubjectSubscriber;
6084 }(Subscriber_1.Subscriber));
6085 exports.SubjectSubscriber = SubjectSubscriber;
6089 var Subject = (function (_super) {
6090 __extends(Subject, _super);
6091 function Subject() {
6093 this.observers = [];
6094 this.closed = false;
6095 this.isStopped = false;
6096 this.hasError = false;
6097 this.thrownError = null;
6099 Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
6100 return new SubjectSubscriber(this);
6102 Subject.prototype.lift = function (operator) {
6103 var subject = new AnonymousSubject(this, this);
6104 subject.operator = operator;
6107 Subject.prototype.next = function (value) {
6109 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6111 if (!this.isStopped) {
6112 var observers = this.observers;
6113 var len = observers.length;
6114 var copy = observers.slice();
6115 for (var i = 0; i < len; i++) {
6116 copy[i].next(value);
6120 Subject.prototype.error = function (err) {
6122 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6124 this.hasError = true;
6125 this.thrownError = err;
6126 this.isStopped = true;
6127 var observers = this.observers;
6128 var len = observers.length;
6129 var copy = observers.slice();
6130 for (var i = 0; i < len; i++) {
6133 this.observers.length = 0;
6135 Subject.prototype.complete = function () {
6137 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6139 this.isStopped = true;
6140 var observers = this.observers;
6141 var len = observers.length;
6142 var copy = observers.slice();
6143 for (var i = 0; i < len; i++) {
6146 this.observers.length = 0;
6148 Subject.prototype.unsubscribe = function () {
6149 this.isStopped = true;
6151 this.observers = null;
6153 Subject.prototype._trySubscribe = function (subscriber) {
6155 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6158 return _super.prototype._trySubscribe.call(this, subscriber);
6161 Subject.prototype._subscribe = function (subscriber) {
6163 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6165 else if (this.hasError) {
6166 subscriber.error(this.thrownError);
6167 return Subscription_1.Subscription.EMPTY;
6169 else if (this.isStopped) {
6170 subscriber.complete();
6171 return Subscription_1.Subscription.EMPTY;
6174 this.observers.push(subscriber);
6175 return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6178 Subject.prototype.asObservable = function () {
6179 var observable = new Observable_1.Observable();
6180 observable.source = this;
6183 Subject.create = function (destination, source) {
6184 return new AnonymousSubject(destination, source);
6187 }(Observable_1.Observable));
6188 exports.Subject = Subject;
6190 * @class AnonymousSubject<T>
6192 var AnonymousSubject = (function (_super) {
6193 __extends(AnonymousSubject, _super);
6194 function AnonymousSubject(destination, source) {
6196 this.destination = destination;
6197 this.source = source;
6199 AnonymousSubject.prototype.next = function (value) {
6200 var destination = this.destination;
6201 if (destination && destination.next) {
6202 destination.next(value);
6205 AnonymousSubject.prototype.error = function (err) {
6206 var destination = this.destination;
6207 if (destination && destination.error) {
6208 this.destination.error(err);
6211 AnonymousSubject.prototype.complete = function () {
6212 var destination = this.destination;
6213 if (destination && destination.complete) {
6214 this.destination.complete();
6217 AnonymousSubject.prototype._subscribe = function (subscriber) {
6218 var source = this.source;
6220 return this.source.subscribe(subscriber);
6223 return Subscription_1.Subscription.EMPTY;
6226 return AnonymousSubject;
6228 exports.AnonymousSubject = AnonymousSubject;
6230 },{"./Observable":29,"./SubjectSubscription":35,"./Subscriber":36,"./Subscription":37,"./symbol/rxSubscriber":207,"./util/ObjectUnsubscribedError":211}],35:[function(require,module,exports){
6232 var __extends = (this && this.__extends) || function (d, b) {
6233 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6234 function __() { this.constructor = d; }
6235 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6237 var Subscription_1 = require('./Subscription');
6239 * We need this JSDoc comment for affecting ESDoc.
6241 * @extends {Ignored}
6243 var SubjectSubscription = (function (_super) {
6244 __extends(SubjectSubscription, _super);
6245 function SubjectSubscription(subject, subscriber) {
6247 this.subject = subject;
6248 this.subscriber = subscriber;
6249 this.closed = false;
6251 SubjectSubscription.prototype.unsubscribe = function () {
6256 var subject = this.subject;
6257 var observers = subject.observers;
6258 this.subject = null;
6259 if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
6262 var subscriberIndex = observers.indexOf(this.subscriber);
6263 if (subscriberIndex !== -1) {
6264 observers.splice(subscriberIndex, 1);
6267 return SubjectSubscription;
6268 }(Subscription_1.Subscription));
6269 exports.SubjectSubscription = SubjectSubscription;
6271 },{"./Subscription":37}],36:[function(require,module,exports){
6273 var __extends = (this && this.__extends) || function (d, b) {
6274 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6275 function __() { this.constructor = d; }
6276 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6278 var isFunction_1 = require('./util/isFunction');
6279 var Subscription_1 = require('./Subscription');
6280 var Observer_1 = require('./Observer');
6281 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6283 * Implements the {@link Observer} interface and extends the
6284 * {@link Subscription} class. While the {@link Observer} is the public API for
6285 * consuming the values of an {@link Observable}, all Observers get converted to
6286 * a Subscriber, in order to provide Subscription-like capabilities such as
6287 * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
6288 * implementing operators, but it is rarely used as a public API.
6290 * @class Subscriber<T>
6292 var Subscriber = (function (_super) {
6293 __extends(Subscriber, _super);
6295 * @param {Observer|function(value: T): void} [destinationOrNext] A partially
6296 * defined Observer or a `next` callback function.
6297 * @param {function(e: ?any): void} [error] The `error` callback of an
6299 * @param {function(): void} [complete] The `complete` callback of an
6302 function Subscriber(destinationOrNext, error, complete) {
6304 this.syncErrorValue = null;
6305 this.syncErrorThrown = false;
6306 this.syncErrorThrowable = false;
6307 this.isStopped = false;
6308 switch (arguments.length) {
6310 this.destination = Observer_1.empty;
6313 if (!destinationOrNext) {
6314 this.destination = Observer_1.empty;
6317 if (typeof destinationOrNext === 'object') {
6318 if (destinationOrNext instanceof Subscriber) {
6319 this.destination = destinationOrNext;
6320 this.destination.add(this);
6323 this.syncErrorThrowable = true;
6324 this.destination = new SafeSubscriber(this, destinationOrNext);
6329 this.syncErrorThrowable = true;
6330 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
6334 Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
6336 * A static factory for a Subscriber, given a (potentially partial) definition
6338 * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6339 * @param {function(e: ?any): void} [error] The `error` callback of an
6341 * @param {function(): void} [complete] The `complete` callback of an
6343 * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6344 * Observer represented by the given arguments.
6346 Subscriber.create = function (next, error, complete) {
6347 var subscriber = new Subscriber(next, error, complete);
6348 subscriber.syncErrorThrowable = false;
6352 * The {@link Observer} callback to receive notifications of type `next` from
6353 * the Observable, with a value. The Observable may call this method 0 or more
6355 * @param {T} [value] The `next` value.
6358 Subscriber.prototype.next = function (value) {
6359 if (!this.isStopped) {
6364 * The {@link Observer} callback to receive notifications of type `error` from
6365 * the Observable, with an attached {@link Error}. Notifies the Observer that
6366 * the Observable has experienced an error condition.
6367 * @param {any} [err] The `error` exception.
6370 Subscriber.prototype.error = function (err) {
6371 if (!this.isStopped) {
6372 this.isStopped = true;
6377 * The {@link Observer} callback to receive a valueless notification of type
6378 * `complete` from the Observable. Notifies the Observer that the Observable
6379 * has finished sending push-based notifications.
6382 Subscriber.prototype.complete = function () {
6383 if (!this.isStopped) {
6384 this.isStopped = true;
6388 Subscriber.prototype.unsubscribe = function () {
6392 this.isStopped = true;
6393 _super.prototype.unsubscribe.call(this);
6395 Subscriber.prototype._next = function (value) {
6396 this.destination.next(value);
6398 Subscriber.prototype._error = function (err) {
6399 this.destination.error(err);
6402 Subscriber.prototype._complete = function () {
6403 this.destination.complete();
6406 Subscriber.prototype._unsubscribeAndRecycle = function () {
6407 var _a = this, _parent = _a._parent, _parents = _a._parents;
6408 this._parent = null;
6409 this._parents = null;
6411 this.closed = false;
6412 this.isStopped = false;
6413 this._parent = _parent;
6414 this._parents = _parents;
6418 }(Subscription_1.Subscription));
6419 exports.Subscriber = Subscriber;
6421 * We need this JSDoc comment for affecting ESDoc.
6423 * @extends {Ignored}
6425 var SafeSubscriber = (function (_super) {
6426 __extends(SafeSubscriber, _super);
6427 function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6429 this._parentSubscriber = _parentSubscriber;
6432 if (isFunction_1.isFunction(observerOrNext)) {
6433 next = observerOrNext;
6435 else if (observerOrNext) {
6436 next = observerOrNext.next;
6437 error = observerOrNext.error;
6438 complete = observerOrNext.complete;
6439 if (observerOrNext !== Observer_1.empty) {
6440 context = Object.create(observerOrNext);
6441 if (isFunction_1.isFunction(context.unsubscribe)) {
6442 this.add(context.unsubscribe.bind(context));
6444 context.unsubscribe = this.unsubscribe.bind(this);
6447 this._context = context;
6449 this._error = error;
6450 this._complete = complete;
6452 SafeSubscriber.prototype.next = function (value) {
6453 if (!this.isStopped && this._next) {
6454 var _parentSubscriber = this._parentSubscriber;
6455 if (!_parentSubscriber.syncErrorThrowable) {
6456 this.__tryOrUnsub(this._next, value);
6458 else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6463 SafeSubscriber.prototype.error = function (err) {
6464 if (!this.isStopped) {
6465 var _parentSubscriber = this._parentSubscriber;
6467 if (!_parentSubscriber.syncErrorThrowable) {
6468 this.__tryOrUnsub(this._error, err);
6472 this.__tryOrSetError(_parentSubscriber, this._error, err);
6476 else if (!_parentSubscriber.syncErrorThrowable) {
6481 _parentSubscriber.syncErrorValue = err;
6482 _parentSubscriber.syncErrorThrown = true;
6487 SafeSubscriber.prototype.complete = function () {
6489 if (!this.isStopped) {
6490 var _parentSubscriber = this._parentSubscriber;
6491 if (this._complete) {
6492 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6493 if (!_parentSubscriber.syncErrorThrowable) {
6494 this.__tryOrUnsub(wrappedComplete);
6498 this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6507 SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6509 fn.call(this._context, value);
6516 SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6518 fn.call(this._context, value);
6521 parent.syncErrorValue = err;
6522 parent.syncErrorThrown = true;
6527 SafeSubscriber.prototype._unsubscribe = function () {
6528 var _parentSubscriber = this._parentSubscriber;
6529 this._context = null;
6530 this._parentSubscriber = null;
6531 _parentSubscriber.unsubscribe();
6533 return SafeSubscriber;
6536 },{"./Observer":30,"./Subscription":37,"./symbol/rxSubscriber":207,"./util/isFunction":220}],37:[function(require,module,exports){
6538 var isArray_1 = require('./util/isArray');
6539 var isObject_1 = require('./util/isObject');
6540 var isFunction_1 = require('./util/isFunction');
6541 var tryCatch_1 = require('./util/tryCatch');
6542 var errorObject_1 = require('./util/errorObject');
6543 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6545 * Represents a disposable resource, such as the execution of an Observable. A
6546 * Subscription has one important method, `unsubscribe`, that takes no argument
6547 * and just disposes the resource held by the subscription.
6549 * Additionally, subscriptions may be grouped together through the `add()`
6550 * method, which will attach a child Subscription to the current Subscription.
6551 * When a Subscription is unsubscribed, all its children (and its grandchildren)
6552 * will be unsubscribed as well.
6554 * @class Subscription
6556 var Subscription = (function () {
6558 * @param {function(): void} [unsubscribe] A function describing how to
6559 * perform the disposal of resources when the `unsubscribe` method is called.
6561 function Subscription(unsubscribe) {
6563 * A flag to indicate whether this Subscription has already been unsubscribed.
6566 this.closed = false;
6567 this._parent = null;
6568 this._parents = null;
6569 this._subscriptions = null;
6571 this._unsubscribe = unsubscribe;
6575 * Disposes the resources held by the subscription. May, for instance, cancel
6576 * an ongoing Observable execution or cancel any other type of work that
6577 * started when the Subscription was created.
6580 Subscription.prototype.unsubscribe = function () {
6581 var hasErrors = false;
6586 var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6588 this._parent = null;
6589 this._parents = null;
6590 // null out _subscriptions first so any child subscriptions that attempt
6591 // to remove themselves from this subscription will noop
6592 this._subscriptions = null;
6594 var len = _parents ? _parents.length : 0;
6595 // if this._parent is null, then so is this._parents, and we
6596 // don't have to remove ourselves from any parent subscriptions.
6598 _parent.remove(this);
6599 // if this._parents is null or index >= len,
6600 // then _parent is set to null, and the loop exits
6601 _parent = ++index < len && _parents[index] || null;
6603 if (isFunction_1.isFunction(_unsubscribe)) {
6604 var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6605 if (trial === errorObject_1.errorObject) {
6607 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6608 flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6611 if (isArray_1.isArray(_subscriptions)) {
6613 len = _subscriptions.length;
6614 while (++index < len) {
6615 var sub = _subscriptions[index];
6616 if (isObject_1.isObject(sub)) {
6617 var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6618 if (trial === errorObject_1.errorObject) {
6620 errors = errors || [];
6621 var err = errorObject_1.errorObject.e;
6622 if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6623 errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6633 throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6637 * Adds a tear down to be called during the unsubscribe() of this
6640 * If the tear down being added is a subscription that is already
6641 * unsubscribed, is the same reference `add` is being called on, or is
6642 * `Subscription.EMPTY`, it will not be added.
6644 * If this subscription is already in an `closed` state, the passed
6645 * tear down logic will be executed immediately.
6647 * @param {TeardownLogic} teardown The additional logic to execute on
6649 * @return {Subscription} Returns the Subscription used or created to be
6650 * added to the inner subscriptions list. This Subscription can be used with
6651 * `remove()` to remove the passed teardown logic from the inner subscriptions
6654 Subscription.prototype.add = function (teardown) {
6655 if (!teardown || (teardown === Subscription.EMPTY)) {
6656 return Subscription.EMPTY;
6658 if (teardown === this) {
6661 var subscription = teardown;
6662 switch (typeof teardown) {
6664 subscription = new Subscription(teardown);
6666 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6667 return subscription;
6669 else if (this.closed) {
6670 subscription.unsubscribe();
6671 return subscription;
6673 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6674 var tmp = subscription;
6675 subscription = new Subscription();
6676 subscription._subscriptions = [tmp];
6680 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6682 var subscriptions = this._subscriptions || (this._subscriptions = []);
6683 subscriptions.push(subscription);
6684 subscription._addParent(this);
6685 return subscription;
6688 * Removes a Subscription from the internal list of subscriptions that will
6689 * unsubscribe during the unsubscribe process of this Subscription.
6690 * @param {Subscription} subscription The subscription to remove.
6693 Subscription.prototype.remove = function (subscription) {
6694 var subscriptions = this._subscriptions;
6695 if (subscriptions) {
6696 var subscriptionIndex = subscriptions.indexOf(subscription);
6697 if (subscriptionIndex !== -1) {
6698 subscriptions.splice(subscriptionIndex, 1);
6702 Subscription.prototype._addParent = function (parent) {
6703 var _a = this, _parent = _a._parent, _parents = _a._parents;
6704 if (!_parent || _parent === parent) {
6705 // If we don't have a parent, or the new parent is the same as the
6706 // current parent, then set this._parent to the new parent.
6707 this._parent = parent;
6709 else if (!_parents) {
6710 // If there's already one parent, but not multiple, allocate an Array to
6711 // store the rest of the parent Subscriptions.
6712 this._parents = [parent];
6714 else if (_parents.indexOf(parent) === -1) {
6715 // Only add the new parent to the _parents list if it's not already there.
6716 _parents.push(parent);
6719 Subscription.EMPTY = (function (empty) {
6720 empty.closed = true;
6722 }(new Subscription()));
6723 return Subscription;
6725 exports.Subscription = Subscription;
6726 function flattenUnsubscriptionErrors(errors) {
6727 return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6730 },{"./util/UnsubscriptionError":214,"./util/errorObject":215,"./util/isArray":217,"./util/isFunction":220,"./util/isObject":222,"./util/tryCatch":230}],38:[function(require,module,exports){
6732 var Observable_1 = require('../../Observable');
6733 var combineLatest_1 = require('../../observable/combineLatest');
6734 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6736 },{"../../Observable":29,"../../observable/combineLatest":101}],39:[function(require,module,exports){
6738 var Observable_1 = require('../../Observable');
6739 var defer_1 = require('../../observable/defer');
6740 Observable_1.Observable.defer = defer_1.defer;
6742 },{"../../Observable":29,"../../observable/defer":103}],40:[function(require,module,exports){
6744 var Observable_1 = require('../../Observable');
6745 var empty_1 = require('../../observable/empty');
6746 Observable_1.Observable.empty = empty_1.empty;
6748 },{"../../Observable":29,"../../observable/empty":104}],41:[function(require,module,exports){
6750 var Observable_1 = require('../../Observable');
6751 var from_1 = require('../../observable/from');
6752 Observable_1.Observable.from = from_1.from;
6754 },{"../../Observable":29,"../../observable/from":105}],42:[function(require,module,exports){
6756 var Observable_1 = require('../../Observable');
6757 var fromEvent_1 = require('../../observable/fromEvent');
6758 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6760 },{"../../Observable":29,"../../observable/fromEvent":106}],43:[function(require,module,exports){
6762 var Observable_1 = require('../../Observable');
6763 var fromPromise_1 = require('../../observable/fromPromise');
6764 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6766 },{"../../Observable":29,"../../observable/fromPromise":107}],44:[function(require,module,exports){
6768 var Observable_1 = require('../../Observable');
6769 var merge_1 = require('../../observable/merge');
6770 Observable_1.Observable.merge = merge_1.merge;
6772 },{"../../Observable":29,"../../observable/merge":108}],45:[function(require,module,exports){
6774 var Observable_1 = require('../../Observable');
6775 var of_1 = require('../../observable/of');
6776 Observable_1.Observable.of = of_1.of;
6778 },{"../../Observable":29,"../../observable/of":109}],46:[function(require,module,exports){
6780 var Observable_1 = require('../../Observable');
6781 var throw_1 = require('../../observable/throw');
6782 Observable_1.Observable.throw = throw_1._throw;
6784 },{"../../Observable":29,"../../observable/throw":110}],47:[function(require,module,exports){
6786 var Observable_1 = require('../../Observable');
6787 var timer_1 = require('../../observable/timer');
6788 Observable_1.Observable.timer = timer_1.timer;
6790 },{"../../Observable":29,"../../observable/timer":111}],48:[function(require,module,exports){
6792 var Observable_1 = require('../../Observable');
6793 var zip_1 = require('../../observable/zip');
6794 Observable_1.Observable.zip = zip_1.zip;
6796 },{"../../Observable":29,"../../observable/zip":112}],49:[function(require,module,exports){
6798 var Observable_1 = require('../../Observable');
6799 var buffer_1 = require('../../operator/buffer');
6800 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6802 },{"../../Observable":29,"../../operator/buffer":113}],50:[function(require,module,exports){
6804 var Observable_1 = require('../../Observable');
6805 var bufferCount_1 = require('../../operator/bufferCount');
6806 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6808 },{"../../Observable":29,"../../operator/bufferCount":114}],51:[function(require,module,exports){
6810 var Observable_1 = require('../../Observable');
6811 var bufferWhen_1 = require('../../operator/bufferWhen');
6812 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6814 },{"../../Observable":29,"../../operator/bufferWhen":115}],52:[function(require,module,exports){
6816 var Observable_1 = require('../../Observable');
6817 var catch_1 = require('../../operator/catch');
6818 Observable_1.Observable.prototype.catch = catch_1._catch;
6819 Observable_1.Observable.prototype._catch = catch_1._catch;
6821 },{"../../Observable":29,"../../operator/catch":116}],53:[function(require,module,exports){
6823 var Observable_1 = require('../../Observable');
6824 var combineLatest_1 = require('../../operator/combineLatest');
6825 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6827 },{"../../Observable":29,"../../operator/combineLatest":117}],54:[function(require,module,exports){
6829 var Observable_1 = require('../../Observable');
6830 var concat_1 = require('../../operator/concat');
6831 Observable_1.Observable.prototype.concat = concat_1.concat;
6833 },{"../../Observable":29,"../../operator/concat":118}],55:[function(require,module,exports){
6835 var Observable_1 = require('../../Observable');
6836 var debounceTime_1 = require('../../operator/debounceTime');
6837 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6839 },{"../../Observable":29,"../../operator/debounceTime":119}],56:[function(require,module,exports){
6841 var Observable_1 = require('../../Observable');
6842 var delay_1 = require('../../operator/delay');
6843 Observable_1.Observable.prototype.delay = delay_1.delay;
6845 },{"../../Observable":29,"../../operator/delay":120}],57:[function(require,module,exports){
6847 var Observable_1 = require('../../Observable');
6848 var distinct_1 = require('../../operator/distinct');
6849 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6851 },{"../../Observable":29,"../../operator/distinct":121}],58:[function(require,module,exports){
6853 var Observable_1 = require('../../Observable');
6854 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6855 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6857 },{"../../Observable":29,"../../operator/distinctUntilChanged":122}],59:[function(require,module,exports){
6859 var Observable_1 = require('../../Observable');
6860 var do_1 = require('../../operator/do');
6861 Observable_1.Observable.prototype.do = do_1._do;
6862 Observable_1.Observable.prototype._do = do_1._do;
6864 },{"../../Observable":29,"../../operator/do":123}],60:[function(require,module,exports){
6866 var Observable_1 = require('../../Observable');
6867 var expand_1 = require('../../operator/expand');
6868 Observable_1.Observable.prototype.expand = expand_1.expand;
6870 },{"../../Observable":29,"../../operator/expand":124}],61:[function(require,module,exports){
6872 var Observable_1 = require('../../Observable');
6873 var filter_1 = require('../../operator/filter');
6874 Observable_1.Observable.prototype.filter = filter_1.filter;
6876 },{"../../Observable":29,"../../operator/filter":125}],62:[function(require,module,exports){
6878 var Observable_1 = require('../../Observable');
6879 var finally_1 = require('../../operator/finally');
6880 Observable_1.Observable.prototype.finally = finally_1._finally;
6881 Observable_1.Observable.prototype._finally = finally_1._finally;
6883 },{"../../Observable":29,"../../operator/finally":126}],63:[function(require,module,exports){
6885 var Observable_1 = require('../../Observable');
6886 var first_1 = require('../../operator/first');
6887 Observable_1.Observable.prototype.first = first_1.first;
6889 },{"../../Observable":29,"../../operator/first":127}],64:[function(require,module,exports){
6891 var Observable_1 = require('../../Observable');
6892 var last_1 = require('../../operator/last');
6893 Observable_1.Observable.prototype.last = last_1.last;
6895 },{"../../Observable":29,"../../operator/last":128}],65:[function(require,module,exports){
6897 var Observable_1 = require('../../Observable');
6898 var map_1 = require('../../operator/map');
6899 Observable_1.Observable.prototype.map = map_1.map;
6901 },{"../../Observable":29,"../../operator/map":129}],66:[function(require,module,exports){
6903 var Observable_1 = require('../../Observable');
6904 var merge_1 = require('../../operator/merge');
6905 Observable_1.Observable.prototype.merge = merge_1.merge;
6907 },{"../../Observable":29,"../../operator/merge":130}],67:[function(require,module,exports){
6909 var Observable_1 = require('../../Observable');
6910 var mergeAll_1 = require('../../operator/mergeAll');
6911 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6913 },{"../../Observable":29,"../../operator/mergeAll":131}],68:[function(require,module,exports){
6915 var Observable_1 = require('../../Observable');
6916 var mergeMap_1 = require('../../operator/mergeMap');
6917 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6918 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6920 },{"../../Observable":29,"../../operator/mergeMap":132}],69:[function(require,module,exports){
6922 var Observable_1 = require('../../Observable');
6923 var pairwise_1 = require('../../operator/pairwise');
6924 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6926 },{"../../Observable":29,"../../operator/pairwise":133}],70:[function(require,module,exports){
6928 var Observable_1 = require('../../Observable');
6929 var pluck_1 = require('../../operator/pluck');
6930 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6932 },{"../../Observable":29,"../../operator/pluck":134}],71:[function(require,module,exports){
6934 var Observable_1 = require('../../Observable');
6935 var publish_1 = require('../../operator/publish');
6936 Observable_1.Observable.prototype.publish = publish_1.publish;
6938 },{"../../Observable":29,"../../operator/publish":135}],72:[function(require,module,exports){
6940 var Observable_1 = require('../../Observable');
6941 var publishReplay_1 = require('../../operator/publishReplay');
6942 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6944 },{"../../Observable":29,"../../operator/publishReplay":136}],73:[function(require,module,exports){
6946 var Observable_1 = require('../../Observable');
6947 var retry_1 = require('../../operator/retry');
6948 Observable_1.Observable.prototype.retry = retry_1.retry;
6950 },{"../../Observable":29,"../../operator/retry":137}],74:[function(require,module,exports){
6952 var Observable_1 = require('../../Observable');
6953 var sample_1 = require('../../operator/sample');
6954 Observable_1.Observable.prototype.sample = sample_1.sample;
6956 },{"../../Observable":29,"../../operator/sample":138}],75:[function(require,module,exports){
6958 var Observable_1 = require('../../Observable');
6959 var scan_1 = require('../../operator/scan');
6960 Observable_1.Observable.prototype.scan = scan_1.scan;
6962 },{"../../Observable":29,"../../operator/scan":139}],76:[function(require,module,exports){
6964 var Observable_1 = require('../../Observable');
6965 var share_1 = require('../../operator/share');
6966 Observable_1.Observable.prototype.share = share_1.share;
6968 },{"../../Observable":29,"../../operator/share":140}],77:[function(require,module,exports){
6970 var Observable_1 = require('../../Observable');
6971 var skip_1 = require('../../operator/skip');
6972 Observable_1.Observable.prototype.skip = skip_1.skip;
6974 },{"../../Observable":29,"../../operator/skip":141}],78:[function(require,module,exports){
6976 var Observable_1 = require('../../Observable');
6977 var skipUntil_1 = require('../../operator/skipUntil');
6978 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6980 },{"../../Observable":29,"../../operator/skipUntil":142}],79:[function(require,module,exports){
6982 var Observable_1 = require('../../Observable');
6983 var skipWhile_1 = require('../../operator/skipWhile');
6984 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
6986 },{"../../Observable":29,"../../operator/skipWhile":143}],80:[function(require,module,exports){
6988 var Observable_1 = require('../../Observable');
6989 var startWith_1 = require('../../operator/startWith');
6990 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6992 },{"../../Observable":29,"../../operator/startWith":144}],81:[function(require,module,exports){
6994 var Observable_1 = require('../../Observable');
6995 var switchMap_1 = require('../../operator/switchMap');
6996 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6998 },{"../../Observable":29,"../../operator/switchMap":145}],82:[function(require,module,exports){
7000 var Observable_1 = require('../../Observable');
7001 var take_1 = require('../../operator/take');
7002 Observable_1.Observable.prototype.take = take_1.take;
7004 },{"../../Observable":29,"../../operator/take":146}],83:[function(require,module,exports){
7006 var Observable_1 = require('../../Observable');
7007 var takeUntil_1 = require('../../operator/takeUntil');
7008 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
7010 },{"../../Observable":29,"../../operator/takeUntil":147}],84:[function(require,module,exports){
7012 var Observable_1 = require('../../Observable');
7013 var takeWhile_1 = require('../../operator/takeWhile');
7014 Observable_1.Observable.prototype.takeWhile = takeWhile_1.takeWhile;
7016 },{"../../Observable":29,"../../operator/takeWhile":148}],85:[function(require,module,exports){
7018 var Observable_1 = require('../../Observable');
7019 var throttleTime_1 = require('../../operator/throttleTime');
7020 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
7022 },{"../../Observable":29,"../../operator/throttleTime":149}],86:[function(require,module,exports){
7024 var Observable_1 = require('../../Observable');
7025 var timeout_1 = require('../../operator/timeout');
7026 Observable_1.Observable.prototype.timeout = timeout_1.timeout;
7028 },{"../../Observable":29,"../../operator/timeout":150}],87:[function(require,module,exports){
7030 var Observable_1 = require('../../Observable');
7031 var withLatestFrom_1 = require('../../operator/withLatestFrom');
7032 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
7034 },{"../../Observable":29,"../../operator/withLatestFrom":151}],88:[function(require,module,exports){
7036 var Observable_1 = require('../../Observable');
7037 var zip_1 = require('../../operator/zip');
7038 Observable_1.Observable.prototype.zip = zip_1.zipProto;
7040 },{"../../Observable":29,"../../operator/zip":152}],89:[function(require,module,exports){
7042 var __extends = (this && this.__extends) || function (d, b) {
7043 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7044 function __() { this.constructor = d; }
7045 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7047 var Observable_1 = require('../Observable');
7048 var ScalarObservable_1 = require('./ScalarObservable');
7049 var EmptyObservable_1 = require('./EmptyObservable');
7051 * We need this JSDoc comment for affecting ESDoc.
7052 * @extends {Ignored}
7055 var ArrayLikeObservable = (function (_super) {
7056 __extends(ArrayLikeObservable, _super);
7057 function ArrayLikeObservable(arrayLike, scheduler) {
7059 this.arrayLike = arrayLike;
7060 this.scheduler = scheduler;
7061 if (!scheduler && arrayLike.length === 1) {
7062 this._isScalar = true;
7063 this.value = arrayLike[0];
7066 ArrayLikeObservable.create = function (arrayLike, scheduler) {
7067 var length = arrayLike.length;
7069 return new EmptyObservable_1.EmptyObservable();
7071 else if (length === 1) {
7072 return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
7075 return new ArrayLikeObservable(arrayLike, scheduler);
7078 ArrayLikeObservable.dispatch = function (state) {
7079 var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
7080 if (subscriber.closed) {
7083 if (index >= length) {
7084 subscriber.complete();
7087 subscriber.next(arrayLike[index]);
7088 state.index = index + 1;
7089 this.schedule(state);
7091 ArrayLikeObservable.prototype._subscribe = function (subscriber) {
7093 var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
7094 var length = arrayLike.length;
7096 return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
7097 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
7101 for (var i = 0; i < length && !subscriber.closed; i++) {
7102 subscriber.next(arrayLike[i]);
7104 subscriber.complete();
7107 return ArrayLikeObservable;
7108 }(Observable_1.Observable));
7109 exports.ArrayLikeObservable = ArrayLikeObservable;
7111 },{"../Observable":29,"./EmptyObservable":93,"./ScalarObservable":99}],90:[function(require,module,exports){
7113 var __extends = (this && this.__extends) || function (d, b) {
7114 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7115 function __() { this.constructor = d; }
7116 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7118 var Observable_1 = require('../Observable');
7119 var ScalarObservable_1 = require('./ScalarObservable');
7120 var EmptyObservable_1 = require('./EmptyObservable');
7121 var isScheduler_1 = require('../util/isScheduler');
7123 * We need this JSDoc comment for affecting ESDoc.
7124 * @extends {Ignored}
7127 var ArrayObservable = (function (_super) {
7128 __extends(ArrayObservable, _super);
7129 function ArrayObservable(array, scheduler) {
7132 this.scheduler = scheduler;
7133 if (!scheduler && array.length === 1) {
7134 this._isScalar = true;
7135 this.value = array[0];
7138 ArrayObservable.create = function (array, scheduler) {
7139 return new ArrayObservable(array, scheduler);
7142 * Creates an Observable that emits some values you specify as arguments,
7143 * immediately one after the other, and then emits a complete notification.
7145 * <span class="informal">Emits the arguments you provide, then completes.
7148 * <img src="./img/of.png" width="100%">
7150 * This static operator is useful for creating a simple Observable that only
7151 * emits the arguments given, and the complete notification thereafter. It can
7152 * be used for composing with other Observables, such as with {@link concat}.
7153 * By default, it uses a `null` IScheduler, which means the `next`
7154 * notifications are sent synchronously, although with a different IScheduler
7155 * it is possible to determine when those notifications will be delivered.
7157 * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
7158 * var numbers = Rx.Observable.of(10, 20, 30);
7159 * var letters = Rx.Observable.of('a', 'b', 'c');
7160 * var interval = Rx.Observable.interval(1000);
7161 * var result = numbers.concat(letters).concat(interval);
7162 * result.subscribe(x => console.log(x));
7164 * @see {@link create}
7165 * @see {@link empty}
7166 * @see {@link never}
7167 * @see {@link throw}
7169 * @param {...T} values Arguments that represent `next` values to be emitted.
7170 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7171 * the emissions of the `next` notifications.
7172 * @return {Observable<T>} An Observable that emits each given input value.
7177 ArrayObservable.of = function () {
7179 for (var _i = 0; _i < arguments.length; _i++) {
7180 array[_i - 0] = arguments[_i];
7182 var scheduler = array[array.length - 1];
7183 if (isScheduler_1.isScheduler(scheduler)) {
7189 var len = array.length;
7191 return new ArrayObservable(array, scheduler);
7193 else if (len === 1) {
7194 return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
7197 return new EmptyObservable_1.EmptyObservable(scheduler);
7200 ArrayObservable.dispatch = function (state) {
7201 var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
7202 if (index >= count) {
7203 subscriber.complete();
7206 subscriber.next(array[index]);
7207 if (subscriber.closed) {
7210 state.index = index + 1;
7211 this.schedule(state);
7213 ArrayObservable.prototype._subscribe = function (subscriber) {
7215 var array = this.array;
7216 var count = array.length;
7217 var scheduler = this.scheduler;
7219 return scheduler.schedule(ArrayObservable.dispatch, 0, {
7220 array: array, index: index, count: count, subscriber: subscriber
7224 for (var i = 0; i < count && !subscriber.closed; i++) {
7225 subscriber.next(array[i]);
7227 subscriber.complete();
7230 return ArrayObservable;
7231 }(Observable_1.Observable));
7232 exports.ArrayObservable = ArrayObservable;
7234 },{"../Observable":29,"../util/isScheduler":224,"./EmptyObservable":93,"./ScalarObservable":99}],91:[function(require,module,exports){
7236 var __extends = (this && this.__extends) || function (d, b) {
7237 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7238 function __() { this.constructor = d; }
7239 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7241 var Subject_1 = require('../Subject');
7242 var Observable_1 = require('../Observable');
7243 var Subscriber_1 = require('../Subscriber');
7244 var Subscription_1 = require('../Subscription');
7245 var refCount_1 = require('../operators/refCount');
7247 * @class ConnectableObservable<T>
7249 var ConnectableObservable = (function (_super) {
7250 __extends(ConnectableObservable, _super);
7251 function ConnectableObservable(source, subjectFactory) {
7253 this.source = source;
7254 this.subjectFactory = subjectFactory;
7256 this._isComplete = false;
7258 ConnectableObservable.prototype._subscribe = function (subscriber) {
7259 return this.getSubject().subscribe(subscriber);
7261 ConnectableObservable.prototype.getSubject = function () {
7262 var subject = this._subject;
7263 if (!subject || subject.isStopped) {
7264 this._subject = this.subjectFactory();
7266 return this._subject;
7268 ConnectableObservable.prototype.connect = function () {
7269 var connection = this._connection;
7271 this._isComplete = false;
7272 connection = this._connection = new Subscription_1.Subscription();
7273 connection.add(this.source
7274 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
7275 if (connection.closed) {
7276 this._connection = null;
7277 connection = Subscription_1.Subscription.EMPTY;
7280 this._connection = connection;
7285 ConnectableObservable.prototype.refCount = function () {
7286 return refCount_1.refCount()(this);
7288 return ConnectableObservable;
7289 }(Observable_1.Observable));
7290 exports.ConnectableObservable = ConnectableObservable;
7291 var connectableProto = ConnectableObservable.prototype;
7292 exports.connectableObservableDescriptor = {
7293 operator: { value: null },
7294 _refCount: { value: 0, writable: true },
7295 _subject: { value: null, writable: true },
7296 _connection: { value: null, writable: true },
7297 _subscribe: { value: connectableProto._subscribe },
7298 _isComplete: { value: connectableProto._isComplete, writable: true },
7299 getSubject: { value: connectableProto.getSubject },
7300 connect: { value: connectableProto.connect },
7301 refCount: { value: connectableProto.refCount }
7303 var ConnectableSubscriber = (function (_super) {
7304 __extends(ConnectableSubscriber, _super);
7305 function ConnectableSubscriber(destination, connectable) {
7306 _super.call(this, destination);
7307 this.connectable = connectable;
7309 ConnectableSubscriber.prototype._error = function (err) {
7310 this._unsubscribe();
7311 _super.prototype._error.call(this, err);
7313 ConnectableSubscriber.prototype._complete = function () {
7314 this.connectable._isComplete = true;
7315 this._unsubscribe();
7316 _super.prototype._complete.call(this);
7318 ConnectableSubscriber.prototype._unsubscribe = function () {
7319 var connectable = this.connectable;
7321 this.connectable = null;
7322 var connection = connectable._connection;
7323 connectable._refCount = 0;
7324 connectable._subject = null;
7325 connectable._connection = null;
7327 connection.unsubscribe();
7331 return ConnectableSubscriber;
7332 }(Subject_1.SubjectSubscriber));
7333 var RefCountOperator = (function () {
7334 function RefCountOperator(connectable) {
7335 this.connectable = connectable;
7337 RefCountOperator.prototype.call = function (subscriber, source) {
7338 var connectable = this.connectable;
7339 connectable._refCount++;
7340 var refCounter = new RefCountSubscriber(subscriber, connectable);
7341 var subscription = source.subscribe(refCounter);
7342 if (!refCounter.closed) {
7343 refCounter.connection = connectable.connect();
7345 return subscription;
7347 return RefCountOperator;
7349 var RefCountSubscriber = (function (_super) {
7350 __extends(RefCountSubscriber, _super);
7351 function RefCountSubscriber(destination, connectable) {
7352 _super.call(this, destination);
7353 this.connectable = connectable;
7355 RefCountSubscriber.prototype._unsubscribe = function () {
7356 var connectable = this.connectable;
7358 this.connection = null;
7361 this.connectable = null;
7362 var refCount = connectable._refCount;
7363 if (refCount <= 0) {
7364 this.connection = null;
7367 connectable._refCount = refCount - 1;
7369 this.connection = null;
7373 // Compare the local RefCountSubscriber's connection Subscription to the
7374 // connection Subscription on the shared ConnectableObservable. In cases
7375 // where the ConnectableObservable source synchronously emits values, and
7376 // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
7377 // execution continues to here before the RefCountOperator has a chance to
7378 // supply the RefCountSubscriber with the shared connection Subscription.
7381 // Observable.range(0, 10)
7387 // In order to account for this case, RefCountSubscriber should only dispose
7388 // the ConnectableObservable's shared connection Subscription if the
7389 // connection Subscription exists, *and* either:
7390 // a. RefCountSubscriber doesn't have a reference to the shared connection
7391 // Subscription yet, or,
7392 // b. RefCountSubscriber's connection Subscription reference is identical
7393 // to the shared connection Subscription
7395 var connection = this.connection;
7396 var sharedConnection = connectable._connection;
7397 this.connection = null;
7398 if (sharedConnection && (!connection || sharedConnection === connection)) {
7399 sharedConnection.unsubscribe();
7402 return RefCountSubscriber;
7403 }(Subscriber_1.Subscriber));
7405 },{"../Observable":29,"../Subject":34,"../Subscriber":36,"../Subscription":37,"../operators/refCount":179}],92:[function(require,module,exports){
7407 var __extends = (this && this.__extends) || function (d, b) {
7408 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7409 function __() { this.constructor = d; }
7410 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7412 var Observable_1 = require('../Observable');
7413 var subscribeToResult_1 = require('../util/subscribeToResult');
7414 var OuterSubscriber_1 = require('../OuterSubscriber');
7416 * We need this JSDoc comment for affecting ESDoc.
7417 * @extends {Ignored}
7420 var DeferObservable = (function (_super) {
7421 __extends(DeferObservable, _super);
7422 function DeferObservable(observableFactory) {
7424 this.observableFactory = observableFactory;
7427 * Creates an Observable that, on subscribe, calls an Observable factory to
7428 * make an Observable for each new Observer.
7430 * <span class="informal">Creates the Observable lazily, that is, only when it
7434 * <img src="./img/defer.png" width="100%">
7436 * `defer` allows you to create the Observable only when the Observer
7437 * subscribes, and create a fresh Observable for each Observer. It waits until
7438 * an Observer subscribes to it, and then it generates an Observable,
7439 * typically with an Observable factory function. It does this afresh for each
7440 * subscriber, so although each subscriber may think it is subscribing to the
7441 * same Observable, in fact each subscriber gets its own individual
7444 * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7445 * var clicksOrInterval = Rx.Observable.defer(function () {
7446 * if (Math.random() > 0.5) {
7447 * return Rx.Observable.fromEvent(document, 'click');
7449 * return Rx.Observable.interval(1000);
7452 * clicksOrInterval.subscribe(x => console.log(x));
7454 * // Results in the following behavior:
7455 * // If the result of Math.random() is greater than 0.5 it will listen
7456 * // for clicks anywhere on the "document"; when document is clicked it
7457 * // will log a MouseEvent object to the console. If the result is less
7458 * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7460 * @see {@link create}
7462 * @param {function(): SubscribableOrPromise} observableFactory The Observable
7463 * factory function to invoke for each Observer that subscribes to the output
7464 * Observable. May also return a Promise, which will be converted on the fly
7466 * @return {Observable} An Observable whose Observers' subscriptions trigger
7467 * an invocation of the given Observable factory function.
7472 DeferObservable.create = function (observableFactory) {
7473 return new DeferObservable(observableFactory);
7475 DeferObservable.prototype._subscribe = function (subscriber) {
7476 return new DeferSubscriber(subscriber, this.observableFactory);
7478 return DeferObservable;
7479 }(Observable_1.Observable));
7480 exports.DeferObservable = DeferObservable;
7481 var DeferSubscriber = (function (_super) {
7482 __extends(DeferSubscriber, _super);
7483 function DeferSubscriber(destination, factory) {
7484 _super.call(this, destination);
7485 this.factory = factory;
7488 DeferSubscriber.prototype.tryDefer = function () {
7490 this._callFactory();
7496 DeferSubscriber.prototype._callFactory = function () {
7497 var result = this.factory();
7499 this.add(subscribeToResult_1.subscribeToResult(this, result));
7502 return DeferSubscriber;
7503 }(OuterSubscriber_1.OuterSubscriber));
7505 },{"../Observable":29,"../OuterSubscriber":31,"../util/subscribeToResult":228}],93:[function(require,module,exports){
7507 var __extends = (this && this.__extends) || function (d, b) {
7508 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7509 function __() { this.constructor = d; }
7510 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7512 var Observable_1 = require('../Observable');
7514 * We need this JSDoc comment for affecting ESDoc.
7515 * @extends {Ignored}
7518 var EmptyObservable = (function (_super) {
7519 __extends(EmptyObservable, _super);
7520 function EmptyObservable(scheduler) {
7522 this.scheduler = scheduler;
7525 * Creates an Observable that emits no items to the Observer and immediately
7526 * emits a complete notification.
7528 * <span class="informal">Just emits 'complete', and nothing else.
7531 * <img src="./img/empty.png" width="100%">
7533 * This static operator is useful for creating a simple Observable that only
7534 * emits the complete notification. It can be used for composing with other
7535 * Observables, such as in a {@link mergeMap}.
7537 * @example <caption>Emit the number 7, then complete.</caption>
7538 * var result = Rx.Observable.empty().startWith(7);
7539 * result.subscribe(x => console.log(x));
7541 * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7542 * var interval = Rx.Observable.interval(1000);
7543 * var result = interval.mergeMap(x =>
7544 * x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7546 * result.subscribe(x => console.log(x));
7548 * // Results in the following to the console:
7549 * // x is equal to the count on the interval eg(0,1,2,3,...)
7550 * // x will occur every 1000ms
7551 * // if x % 2 is equal to 1 print abc
7552 * // if x % 2 is not equal to 1 nothing will be output
7554 * @see {@link create}
7555 * @see {@link never}
7557 * @see {@link throw}
7559 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7560 * the emission of the complete notification.
7561 * @return {Observable} An "empty" Observable: emits only the complete
7567 EmptyObservable.create = function (scheduler) {
7568 return new EmptyObservable(scheduler);
7570 EmptyObservable.dispatch = function (arg) {
7571 var subscriber = arg.subscriber;
7572 subscriber.complete();
7574 EmptyObservable.prototype._subscribe = function (subscriber) {
7575 var scheduler = this.scheduler;
7577 return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7580 subscriber.complete();
7583 return EmptyObservable;
7584 }(Observable_1.Observable));
7585 exports.EmptyObservable = EmptyObservable;
7587 },{"../Observable":29}],94:[function(require,module,exports){
7589 var __extends = (this && this.__extends) || function (d, b) {
7590 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7591 function __() { this.constructor = d; }
7592 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7594 var Observable_1 = require('../Observable');
7596 * We need this JSDoc comment for affecting ESDoc.
7597 * @extends {Ignored}
7600 var ErrorObservable = (function (_super) {
7601 __extends(ErrorObservable, _super);
7602 function ErrorObservable(error, scheduler) {
7605 this.scheduler = scheduler;
7608 * Creates an Observable that emits no items to the Observer and immediately
7609 * emits an error notification.
7611 * <span class="informal">Just emits 'error', and nothing else.
7614 * <img src="./img/throw.png" width="100%">
7616 * This static operator is useful for creating a simple Observable that only
7617 * emits the error notification. It can be used for composing with other
7618 * Observables, such as in a {@link mergeMap}.
7620 * @example <caption>Emit the number 7, then emit an error.</caption>
7621 * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7622 * result.subscribe(x => console.log(x), e => console.error(e));
7624 * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7625 * var interval = Rx.Observable.interval(1000);
7626 * var result = interval.mergeMap(x =>
7628 * Rx.Observable.throw('Thirteens are bad') :
7629 * Rx.Observable.of('a', 'b', 'c')
7631 * result.subscribe(x => console.log(x), e => console.error(e));
7633 * @see {@link create}
7634 * @see {@link empty}
7635 * @see {@link never}
7638 * @param {any} error The particular Error to pass to the error notification.
7639 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7640 * the emission of the error notification.
7641 * @return {Observable} An error Observable: emits only the error notification
7642 * using the given error argument.
7647 ErrorObservable.create = function (error, scheduler) {
7648 return new ErrorObservable(error, scheduler);
7650 ErrorObservable.dispatch = function (arg) {
7651 var error = arg.error, subscriber = arg.subscriber;
7652 subscriber.error(error);
7654 ErrorObservable.prototype._subscribe = function (subscriber) {
7655 var error = this.error;
7656 var scheduler = this.scheduler;
7657 subscriber.syncErrorThrowable = true;
7659 return scheduler.schedule(ErrorObservable.dispatch, 0, {
7660 error: error, subscriber: subscriber
7664 subscriber.error(error);
7667 return ErrorObservable;
7668 }(Observable_1.Observable));
7669 exports.ErrorObservable = ErrorObservable;
7671 },{"../Observable":29}],95:[function(require,module,exports){
7673 var __extends = (this && this.__extends) || function (d, b) {
7674 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7675 function __() { this.constructor = d; }
7676 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7678 var Observable_1 = require('../Observable');
7679 var tryCatch_1 = require('../util/tryCatch');
7680 var isFunction_1 = require('../util/isFunction');
7681 var errorObject_1 = require('../util/errorObject');
7682 var Subscription_1 = require('../Subscription');
7683 var toString = Object.prototype.toString;
7684 function isNodeStyleEventEmitter(sourceObj) {
7685 return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7687 function isJQueryStyleEventEmitter(sourceObj) {
7688 return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7690 function isNodeList(sourceObj) {
7691 return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7693 function isHTMLCollection(sourceObj) {
7694 return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7696 function isEventTarget(sourceObj) {
7697 return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7700 * We need this JSDoc comment for affecting ESDoc.
7701 * @extends {Ignored}
7704 var FromEventObservable = (function (_super) {
7705 __extends(FromEventObservable, _super);
7706 function FromEventObservable(sourceObj, eventName, selector, options) {
7708 this.sourceObj = sourceObj;
7709 this.eventName = eventName;
7710 this.selector = selector;
7711 this.options = options;
7713 /* tslint:enable:max-line-length */
7715 * Creates an Observable that emits events of a specific type coming from the
7716 * given event target.
7718 * <span class="informal">Creates an Observable from DOM events, or Node.js
7719 * EventEmitter events or others.</span>
7721 * <img src="./img/fromEvent.png" width="100%">
7723 * `fromEvent` accepts as a first argument event target, which is an object with methods
7724 * for registering event handler functions. As a second argument it takes string that indicates
7725 * type of event we want to listen for. `fromEvent` supports selected types of event targets,
7726 * which are described in detail below. If your event target does not match any of the ones listed,
7727 * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
7728 * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
7729 * handler functions have different names, but they all accept a string describing event type
7730 * and function itself, which will be called whenever said event happens.
7732 * Every time resulting Observable is subscribed, event handler function will be registered
7733 * to event target on given event type. When that event fires, value
7734 * passed as a first argument to registered function will be emitted by output Observable.
7735 * When Observable is unsubscribed, function will be unregistered from event target.
7737 * Note that if event target calls registered function with more than one argument, second
7738 * and following arguments will not appear in resulting stream. In order to get access to them,
7739 * you can pass to `fromEvent` optional project function, which will be called with all arguments
7740 * passed to event handler. Output Observable will then emit value returned by project function,
7741 * instead of the usual value.
7743 * Remember that event targets listed below are checked via duck typing. It means that
7744 * no matter what kind of object you have and no matter what environment you work in,
7745 * you can safely use `fromEvent` on that object if it exposes described methods (provided
7746 * of course they behave as was described above). So for example if Node.js library exposes
7747 * event target which has the same method names as DOM EventTarget, `fromEvent` is still
7750 * If the API you use is more callback then event handler oriented (subscribed
7751 * callback function fires only once and thus there is no need to manually
7752 * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
7755 * `fromEvent` supports following types of event targets:
7757 * **DOM EventTarget**
7759 * This is an object with `addEventListener` and `removeEventListener` methods.
7761 * In the browser, `addEventListener` accepts - apart from event type string and event
7762 * handler function arguments - optional third parameter, which is either an object or boolean,
7763 * both used for additional configuration how and when passed function will be called. When
7764 * `fromEvent` is used with event target of that type, you can provide this values
7765 * as third parameter as well.
7767 * **Node.js EventEmitter**
7769 * An object with `addListener` and `removeListener` methods.
7771 * **JQuery-style event target**
7773 * An object with `on` and `off` methods
7777 * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
7779 * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
7780 * it contains and install event handler function in every of them. When returned Observable
7781 * is unsubscribed, function will be removed from all Nodes.
7783 * **DOM HtmlCollection**
7785 * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
7786 * installed and removed in each of elements.
7789 * @example <caption>Emits clicks happening on the DOM document</caption>
7790 * var clicks = Rx.Observable.fromEvent(document, 'click');
7791 * clicks.subscribe(x => console.log(x));
7794 * // MouseEvent object logged to console every time a click
7795 * // occurs on the document.
7798 * @example <caption>Use addEventListener with capture option</caption>
7799 * var clicksInDocument = Rx.Observable.fromEvent(document, 'click', true); // note optional configuration parameter
7800 * // which will be passed to addEventListener
7801 * var clicksInDiv = Rx.Observable.fromEvent(someDivInDocument, 'click');
7803 * clicksInDocument.subscribe(() => console.log('document'));
7804 * clicksInDiv.subscribe(() => console.log('div'));
7806 * // By default events bubble UP in DOM tree, so normally
7807 * // when we would click on div in document
7808 * // "div" would be logged first and then "document".
7809 * // Since we specified optional `capture` option, document
7810 * // will catch event when it goes DOWN DOM tree, so console
7811 * // will log "document" and then "div".
7813 * @see {@link bindCallback}
7814 * @see {@link bindNodeCallback}
7815 * @see {@link fromEventPattern}
7817 * @param {EventTargetLike} target The DOM EventTarget, Node.js
7818 * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.
7819 * @param {string} eventName The event name of interest, being emitted by the
7821 * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7822 * @param {SelectorMethodSignature<T>} [selector] An optional function to
7823 * post-process results. It takes the arguments from the event handler and
7824 * should return a single value.
7825 * @return {Observable<T>}
7830 FromEventObservable.create = function (target, eventName, options, selector) {
7831 if (isFunction_1.isFunction(options)) {
7833 options = undefined;
7835 return new FromEventObservable(target, eventName, selector, options);
7837 FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7839 if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7840 for (var i = 0, len = sourceObj.length; i < len; i++) {
7841 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7844 else if (isEventTarget(sourceObj)) {
7845 var source_1 = sourceObj;
7846 sourceObj.addEventListener(eventName, handler, options);
7847 unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7849 else if (isJQueryStyleEventEmitter(sourceObj)) {
7850 var source_2 = sourceObj;
7851 sourceObj.on(eventName, handler);
7852 unsubscribe = function () { return source_2.off(eventName, handler); };
7854 else if (isNodeStyleEventEmitter(sourceObj)) {
7855 var source_3 = sourceObj;
7856 sourceObj.addListener(eventName, handler);
7857 unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7860 throw new TypeError('Invalid event target');
7862 subscriber.add(new Subscription_1.Subscription(unsubscribe));
7864 FromEventObservable.prototype._subscribe = function (subscriber) {
7865 var sourceObj = this.sourceObj;
7866 var eventName = this.eventName;
7867 var options = this.options;
7868 var selector = this.selector;
7869 var handler = selector ? function () {
7871 for (var _i = 0; _i < arguments.length; _i++) {
7872 args[_i - 0] = arguments[_i];
7874 var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7875 if (result === errorObject_1.errorObject) {
7876 subscriber.error(errorObject_1.errorObject.e);
7879 subscriber.next(result);
7881 } : function (e) { return subscriber.next(e); };
7882 FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7884 return FromEventObservable;
7885 }(Observable_1.Observable));
7886 exports.FromEventObservable = FromEventObservable;
7888 },{"../Observable":29,"../Subscription":37,"../util/errorObject":215,"../util/isFunction":220,"../util/tryCatch":230}],96:[function(require,module,exports){
7890 var __extends = (this && this.__extends) || function (d, b) {
7891 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7892 function __() { this.constructor = d; }
7893 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7895 var isArray_1 = require('../util/isArray');
7896 var isArrayLike_1 = require('../util/isArrayLike');
7897 var isPromise_1 = require('../util/isPromise');
7898 var PromiseObservable_1 = require('./PromiseObservable');
7899 var IteratorObservable_1 = require('./IteratorObservable');
7900 var ArrayObservable_1 = require('./ArrayObservable');
7901 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7902 var iterator_1 = require('../symbol/iterator');
7903 var Observable_1 = require('../Observable');
7904 var observeOn_1 = require('../operators/observeOn');
7905 var observable_1 = require('../symbol/observable');
7907 * We need this JSDoc comment for affecting ESDoc.
7908 * @extends {Ignored}
7911 var FromObservable = (function (_super) {
7912 __extends(FromObservable, _super);
7913 function FromObservable(ish, scheduler) {
7914 _super.call(this, null);
7916 this.scheduler = scheduler;
7919 * Creates an Observable from an Array, an array-like object, a Promise, an
7920 * iterable object, or an Observable-like object.
7922 * <span class="informal">Converts almost anything to an Observable.</span>
7924 * <img src="./img/from.png" width="100%">
7926 * Convert various other objects and data types into Observables. `from`
7927 * converts a Promise or an array-like or an
7928 * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7929 * object into an Observable that emits the items in that promise or array or
7930 * iterable. A String, in this context, is treated as an array of characters.
7931 * Observable-like objects (contains a function named with the ES2015 Symbol
7932 * for Observable) can also be converted through this operator.
7934 * @example <caption>Converts an array to an Observable</caption>
7935 * var array = [10, 20, 30];
7936 * var result = Rx.Observable.from(array);
7937 * result.subscribe(x => console.log(x));
7939 * // Results in the following:
7942 * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7943 * function* generateDoubles(seed) {
7947 * i = 2 * i; // double it
7951 * var iterator = generateDoubles(3);
7952 * var result = Rx.Observable.from(iterator).take(10);
7953 * result.subscribe(x => console.log(x));
7955 * // Results in the following:
7956 * // 3 6 12 24 48 96 192 384 768 1536
7958 * @see {@link create}
7959 * @see {@link fromEvent}
7960 * @see {@link fromEventPattern}
7961 * @see {@link fromPromise}
7963 * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7964 * Observable-like, an Array, an iterable or an array-like object to be
7966 * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7967 * emissions of values.
7968 * @return {Observable<T>} The Observable whose values are originally from the
7969 * input object that was converted.
7974 FromObservable.create = function (ish, scheduler) {
7976 if (typeof ish[observable_1.observable] === 'function') {
7977 if (ish instanceof Observable_1.Observable && !scheduler) {
7980 return new FromObservable(ish, scheduler);
7982 else if (isArray_1.isArray(ish)) {
7983 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7985 else if (isPromise_1.isPromise(ish)) {
7986 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7988 else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
7989 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7991 else if (isArrayLike_1.isArrayLike(ish)) {
7992 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7995 throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7997 FromObservable.prototype._subscribe = function (subscriber) {
7999 var scheduler = this.scheduler;
8000 if (scheduler == null) {
8001 return ish[observable_1.observable]().subscribe(subscriber);
8004 return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
8007 return FromObservable;
8008 }(Observable_1.Observable));
8009 exports.FromObservable = FromObservable;
8011 },{"../Observable":29,"../operators/observeOn":174,"../symbol/iterator":205,"../symbol/observable":206,"../util/isArray":217,"../util/isArrayLike":218,"../util/isPromise":223,"./ArrayLikeObservable":89,"./ArrayObservable":90,"./IteratorObservable":97,"./PromiseObservable":98}],97:[function(require,module,exports){
8013 var __extends = (this && this.__extends) || function (d, b) {
8014 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8015 function __() { this.constructor = d; }
8016 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8018 var root_1 = require('../util/root');
8019 var Observable_1 = require('../Observable');
8020 var iterator_1 = require('../symbol/iterator');
8022 * We need this JSDoc comment for affecting ESDoc.
8023 * @extends {Ignored}
8026 var IteratorObservable = (function (_super) {
8027 __extends(IteratorObservable, _super);
8028 function IteratorObservable(iterator, scheduler) {
8030 this.scheduler = scheduler;
8031 if (iterator == null) {
8032 throw new Error('iterator cannot be null.');
8034 this.iterator = getIterator(iterator);
8036 IteratorObservable.create = function (iterator, scheduler) {
8037 return new IteratorObservable(iterator, scheduler);
8039 IteratorObservable.dispatch = function (state) {
8040 var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
8042 subscriber.error(state.error);
8045 var result = iterator.next();
8047 subscriber.complete();
8050 subscriber.next(result.value);
8051 state.index = index + 1;
8052 if (subscriber.closed) {
8053 if (typeof iterator.return === 'function') {
8058 this.schedule(state);
8060 IteratorObservable.prototype._subscribe = function (subscriber) {
8062 var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
8064 return scheduler.schedule(IteratorObservable.dispatch, 0, {
8065 index: index, iterator: iterator, subscriber: subscriber
8070 var result = iterator.next();
8072 subscriber.complete();
8076 subscriber.next(result.value);
8078 if (subscriber.closed) {
8079 if (typeof iterator.return === 'function') {
8087 return IteratorObservable;
8088 }(Observable_1.Observable));
8089 exports.IteratorObservable = IteratorObservable;
8090 var StringIterator = (function () {
8091 function StringIterator(str, idx, len) {
8092 if (idx === void 0) { idx = 0; }
8093 if (len === void 0) { len = str.length; }
8098 StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
8099 StringIterator.prototype.next = function () {
8100 return this.idx < this.len ? {
8102 value: this.str.charAt(this.idx++)
8108 return StringIterator;
8110 var ArrayIterator = (function () {
8111 function ArrayIterator(arr, idx, len) {
8112 if (idx === void 0) { idx = 0; }
8113 if (len === void 0) { len = toLength(arr); }
8118 ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
8119 ArrayIterator.prototype.next = function () {
8120 return this.idx < this.len ? {
8122 value: this.arr[this.idx++]
8128 return ArrayIterator;
8130 function getIterator(obj) {
8131 var i = obj[iterator_1.iterator];
8132 if (!i && typeof obj === 'string') {
8133 return new StringIterator(obj);
8135 if (!i && obj.length !== undefined) {
8136 return new ArrayIterator(obj);
8139 throw new TypeError('object is not iterable');
8141 return obj[iterator_1.iterator]();
8143 var maxSafeInteger = Math.pow(2, 53) - 1;
8144 function toLength(o) {
8145 var len = +o.length;
8149 if (len === 0 || !numberIsFinite(len)) {
8152 len = sign(len) * Math.floor(Math.abs(len));
8156 if (len > maxSafeInteger) {
8157 return maxSafeInteger;
8161 function numberIsFinite(value) {
8162 return typeof value === 'number' && root_1.root.isFinite(value);
8164 function sign(value) {
8165 var valueAsNumber = +value;
8166 if (valueAsNumber === 0) {
8167 return valueAsNumber;
8169 if (isNaN(valueAsNumber)) {
8170 return valueAsNumber;
8172 return valueAsNumber < 0 ? -1 : 1;
8175 },{"../Observable":29,"../symbol/iterator":205,"../util/root":227}],98:[function(require,module,exports){
8177 var __extends = (this && this.__extends) || function (d, b) {
8178 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8179 function __() { this.constructor = d; }
8180 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8182 var root_1 = require('../util/root');
8183 var Observable_1 = require('../Observable');
8185 * We need this JSDoc comment for affecting ESDoc.
8186 * @extends {Ignored}
8189 var PromiseObservable = (function (_super) {
8190 __extends(PromiseObservable, _super);
8191 function PromiseObservable(promise, scheduler) {
8193 this.promise = promise;
8194 this.scheduler = scheduler;
8197 * Converts a Promise to an Observable.
8199 * <span class="informal">Returns an Observable that just emits the Promise's
8200 * resolved value, then completes.</span>
8202 * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
8203 * Observable. If the Promise resolves with a value, the output Observable
8204 * emits that resolved value as a `next`, and then completes. If the Promise
8205 * is rejected, then the output Observable emits the corresponding Error.
8207 * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
8208 * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
8209 * result.subscribe(x => console.log(x), e => console.error(e));
8211 * @see {@link bindCallback}
8214 * @param {PromiseLike<T>} promise The promise to be converted.
8215 * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
8216 * the delivery of the resolved value (or the rejection).
8217 * @return {Observable<T>} An Observable which wraps the Promise.
8222 PromiseObservable.create = function (promise, scheduler) {
8223 return new PromiseObservable(promise, scheduler);
8225 PromiseObservable.prototype._subscribe = function (subscriber) {
8227 var promise = this.promise;
8228 var scheduler = this.scheduler;
8229 if (scheduler == null) {
8230 if (this._isScalar) {
8231 if (!subscriber.closed) {
8232 subscriber.next(this.value);
8233 subscriber.complete();
8237 promise.then(function (value) {
8238 _this.value = value;
8239 _this._isScalar = true;
8240 if (!subscriber.closed) {
8241 subscriber.next(value);
8242 subscriber.complete();
8245 if (!subscriber.closed) {
8246 subscriber.error(err);
8249 .then(null, function (err) {
8250 // escape the promise trap, throw unhandled errors
8251 root_1.root.setTimeout(function () { throw err; });
8256 if (this._isScalar) {
8257 if (!subscriber.closed) {
8258 return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
8262 promise.then(function (value) {
8263 _this.value = value;
8264 _this._isScalar = true;
8265 if (!subscriber.closed) {
8266 subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
8269 if (!subscriber.closed) {
8270 subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
8273 .then(null, function (err) {
8274 // escape the promise trap, throw unhandled errors
8275 root_1.root.setTimeout(function () { throw err; });
8280 return PromiseObservable;
8281 }(Observable_1.Observable));
8282 exports.PromiseObservable = PromiseObservable;
8283 function dispatchNext(arg) {
8284 var value = arg.value, subscriber = arg.subscriber;
8285 if (!subscriber.closed) {
8286 subscriber.next(value);
8287 subscriber.complete();
8290 function dispatchError(arg) {
8291 var err = arg.err, subscriber = arg.subscriber;
8292 if (!subscriber.closed) {
8293 subscriber.error(err);
8297 },{"../Observable":29,"../util/root":227}],99:[function(require,module,exports){
8299 var __extends = (this && this.__extends) || function (d, b) {
8300 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8301 function __() { this.constructor = d; }
8302 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8304 var Observable_1 = require('../Observable');
8306 * We need this JSDoc comment for affecting ESDoc.
8307 * @extends {Ignored}
8310 var ScalarObservable = (function (_super) {
8311 __extends(ScalarObservable, _super);
8312 function ScalarObservable(value, scheduler) {
8315 this.scheduler = scheduler;
8316 this._isScalar = true;
8318 this._isScalar = false;
8321 ScalarObservable.create = function (value, scheduler) {
8322 return new ScalarObservable(value, scheduler);
8324 ScalarObservable.dispatch = function (state) {
8325 var done = state.done, value = state.value, subscriber = state.subscriber;
8327 subscriber.complete();
8330 subscriber.next(value);
8331 if (subscriber.closed) {
8335 this.schedule(state);
8337 ScalarObservable.prototype._subscribe = function (subscriber) {
8338 var value = this.value;
8339 var scheduler = this.scheduler;
8341 return scheduler.schedule(ScalarObservable.dispatch, 0, {
8342 done: false, value: value, subscriber: subscriber
8346 subscriber.next(value);
8347 if (!subscriber.closed) {
8348 subscriber.complete();
8352 return ScalarObservable;
8353 }(Observable_1.Observable));
8354 exports.ScalarObservable = ScalarObservable;
8356 },{"../Observable":29}],100:[function(require,module,exports){
8358 var __extends = (this && this.__extends) || function (d, b) {
8359 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8360 function __() { this.constructor = d; }
8361 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8363 var isNumeric_1 = require('../util/isNumeric');
8364 var Observable_1 = require('../Observable');
8365 var async_1 = require('../scheduler/async');
8366 var isScheduler_1 = require('../util/isScheduler');
8367 var isDate_1 = require('../util/isDate');
8369 * We need this JSDoc comment for affecting ESDoc.
8370 * @extends {Ignored}
8373 var TimerObservable = (function (_super) {
8374 __extends(TimerObservable, _super);
8375 function TimerObservable(dueTime, period, scheduler) {
8376 if (dueTime === void 0) { dueTime = 0; }
8380 if (isNumeric_1.isNumeric(period)) {
8381 this.period = Number(period) < 1 && 1 || Number(period);
8383 else if (isScheduler_1.isScheduler(period)) {
8386 if (!isScheduler_1.isScheduler(scheduler)) {
8387 scheduler = async_1.async;
8389 this.scheduler = scheduler;
8390 this.dueTime = isDate_1.isDate(dueTime) ?
8391 (+dueTime - this.scheduler.now()) :
8395 * Creates an Observable that starts emitting after an `initialDelay` and
8396 * emits ever increasing numbers after each `period` of time thereafter.
8398 * <span class="informal">Its like {@link interval}, but you can specify when
8399 * should the emissions start.</span>
8401 * <img src="./img/timer.png" width="100%">
8403 * `timer` returns an Observable that emits an infinite sequence of ascending
8404 * integers, with a constant interval of time, `period` of your choosing
8405 * between those emissions. The first emission happens after the specified
8406 * `initialDelay`. The initial delay may be a {@link Date}. By default, this
8407 * operator uses the `async` IScheduler to provide a notion of time, but you
8408 * may pass any IScheduler to it. If `period` is not specified, the output
8409 * Observable emits only one value, `0`. Otherwise, it emits an infinite
8412 * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
8413 * var numbers = Rx.Observable.timer(3000, 1000);
8414 * numbers.subscribe(x => console.log(x));
8416 * @example <caption>Emits one number after five seconds</caption>
8417 * var numbers = Rx.Observable.timer(5000);
8418 * numbers.subscribe(x => console.log(x));
8420 * @see {@link interval}
8421 * @see {@link delay}
8423 * @param {number|Date} initialDelay The initial delay time to wait before
8424 * emitting the first value of `0`.
8425 * @param {number} [period] The period of time between emissions of the
8426 * subsequent numbers.
8427 * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
8428 * the emission of values, and providing a notion of "time".
8429 * @return {Observable} An Observable that emits a `0` after the
8430 * `initialDelay` and ever increasing numbers after each `period` of time
8436 TimerObservable.create = function (initialDelay, period, scheduler) {
8437 if (initialDelay === void 0) { initialDelay = 0; }
8438 return new TimerObservable(initialDelay, period, scheduler);
8440 TimerObservable.dispatch = function (state) {
8441 var index = state.index, period = state.period, subscriber = state.subscriber;
8443 subscriber.next(index);
8444 if (subscriber.closed) {
8447 else if (period === -1) {
8448 return subscriber.complete();
8450 state.index = index + 1;
8451 action.schedule(state, period);
8453 TimerObservable.prototype._subscribe = function (subscriber) {
8455 var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
8456 return scheduler.schedule(TimerObservable.dispatch, dueTime, {
8457 index: index, period: period, subscriber: subscriber
8460 return TimerObservable;
8461 }(Observable_1.Observable));
8462 exports.TimerObservable = TimerObservable;
8464 },{"../Observable":29,"../scheduler/async":203,"../util/isDate":219,"../util/isNumeric":221,"../util/isScheduler":224}],101:[function(require,module,exports){
8466 var isScheduler_1 = require('../util/isScheduler');
8467 var isArray_1 = require('../util/isArray');
8468 var ArrayObservable_1 = require('./ArrayObservable');
8469 var combineLatest_1 = require('../operators/combineLatest');
8470 /* tslint:enable:max-line-length */
8472 * Combines multiple Observables to create an Observable whose values are
8473 * calculated from the latest values of each of its input Observables.
8475 * <span class="informal">Whenever any input Observable emits a value, it
8476 * computes a formula using the latest values from all the inputs, then emits
8477 * the output of that formula.</span>
8479 * <img src="./img/combineLatest.png" width="100%">
8481 * `combineLatest` combines the values from all the Observables passed as
8482 * arguments. This is done by subscribing to each Observable in order and,
8483 * whenever any Observable emits, collecting an array of the most recent
8484 * values from each Observable. So if you pass `n` Observables to operator,
8485 * returned Observable will always emit an array of `n` values, in order
8486 * corresponding to order of passed Observables (value from the first Observable
8487 * on the first place and so on).
8489 * Static version of `combineLatest` accepts either an array of Observables
8490 * or each Observable can be put directly as an argument. Note that array of
8491 * Observables is good choice, if you don't know beforehand how many Observables
8492 * you will combine. Passing empty array will result in Observable that
8493 * completes immediately.
8495 * To ensure output array has always the same length, `combineLatest` will
8496 * actually wait for all input Observables to emit at least once,
8497 * before it starts emitting results. This means if some Observable emits
8498 * values before other Observables started emitting, all that values but last
8499 * will be lost. On the other hand, is some Observable does not emit value but
8500 * completes, resulting Observable will complete at the same moment without
8501 * emitting anything, since it will be now impossible to include value from
8502 * completed Observable in resulting array. Also, if some input Observable does
8503 * not emit any value and never completes, `combineLatest` will also never emit
8504 * and never complete, since, again, it will wait for all streams to emit some
8507 * If at least one Observable was passed to `combineLatest` and all passed Observables
8508 * emitted something, resulting Observable will complete when all combined
8509 * streams complete. So even if some Observable completes, result of
8510 * `combineLatest` will still emit values when other Observables do. In case
8511 * of completed Observable, its value from now on will always be the last
8512 * emitted value. On the other hand, if any Observable errors, `combineLatest`
8513 * will error immediately as well, and all other Observables will be unsubscribed.
8515 * `combineLatest` accepts as optional parameter `project` function, which takes
8516 * as arguments all values that would normally be emitted by resulting Observable.
8517 * `project` can return any kind of value, which will be then emitted by Observable
8518 * instead of default array. Note that `project` does not take as argument that array
8519 * of values, but values themselves. That means default `project` can be imagined
8520 * as function that takes all its arguments and puts them into an array.
8523 * @example <caption>Combine two timer Observables</caption>
8524 * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8525 * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8526 * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8527 * combinedTimers.subscribe(value => console.log(value));
8529 * // [0, 0] after 0.5s
8530 * // [1, 0] after 1s
8531 * // [1, 1] after 1.5s
8532 * // [2, 1] after 2s
8535 * @example <caption>Combine an array of Observables</caption>
8536 * const observables = [1, 5, 10].map(
8537 * n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8539 * const combined = Rx.Observable.combineLatest(observables);
8540 * combined.subscribe(value => console.log(value));
8542 * // [0, 0, 0] immediately
8543 * // [1, 0, 0] after 1s
8544 * // [1, 5, 0] after 5s
8545 * // [1, 5, 10] after 10s
8548 * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8549 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8550 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8551 * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8552 * bmi.subscribe(x => console.log('BMI is ' + x));
8554 * // With output to console:
8555 * // BMI is 24.212293388429753
8556 * // BMI is 23.93948099205209
8557 * // BMI is 23.671253629592222
8560 * @see {@link combineAll}
8561 * @see {@link merge}
8562 * @see {@link withLatestFrom}
8564 * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8565 * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8566 * More than one input Observables may be given as arguments
8567 * or an array of Observables may be given as the first argument.
8568 * @param {function} [project] An optional function to project the values from
8569 * the combined latest values into a new value on the output Observable.
8570 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8571 * each input Observable.
8572 * @return {Observable} An Observable of projected values from the most recent
8573 * values from each input Observable, or an array of the most recent values from
8574 * each input Observable.
8576 * @name combineLatest
8579 function combineLatest() {
8580 var observables = [];
8581 for (var _i = 0; _i < arguments.length; _i++) {
8582 observables[_i - 0] = arguments[_i];
8585 var scheduler = null;
8586 if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8587 scheduler = observables.pop();
8589 if (typeof observables[observables.length - 1] === 'function') {
8590 project = observables.pop();
8592 // if the first and only other argument besides the resultSelector is an array
8593 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8594 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8595 observables = observables[0];
8597 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8599 exports.combineLatest = combineLatest;
8601 },{"../operators/combineLatest":157,"../util/isArray":217,"../util/isScheduler":224,"./ArrayObservable":90}],102:[function(require,module,exports){
8603 var isScheduler_1 = require('../util/isScheduler');
8604 var of_1 = require('./of');
8605 var from_1 = require('./from');
8606 var concatAll_1 = require('../operators/concatAll');
8607 /* tslint:enable:max-line-length */
8609 * Creates an output Observable which sequentially emits all values from given
8610 * Observable and then moves on to the next.
8612 * <span class="informal">Concatenates multiple Observables together by
8613 * sequentially emitting their values, one Observable after the other.</span>
8615 * <img src="./img/concat.png" width="100%">
8617 * `concat` joins multiple Observables together, by subscribing to them one at a time and
8618 * merging their results into the output Observable. You can pass either an array of
8619 * Observables, or put them directly as arguments. Passing an empty array will result
8620 * in Observable that completes immediately.
8622 * `concat` will subscribe to first input Observable and emit all its values, without
8623 * changing or affecting them in any way. When that Observable completes, it will
8624 * subscribe to then next Observable passed and, again, emit its values. This will be
8625 * repeated, until the operator runs out of Observables. When last input Observable completes,
8626 * `concat` will complete as well. At any given moment only one Observable passed to operator
8627 * emits values. If you would like to emit values from passed Observables concurrently, check out
8628 * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
8629 * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
8631 * Note that if some input Observable never completes, `concat` will also never complete
8632 * and Observables following the one that did not complete will never be subscribed. On the other
8633 * hand, if some Observable simply completes immediately after it is subscribed, it will be
8634 * invisible for `concat`, which will just move on to the next Observable.
8636 * If any Observable in chain errors, instead of passing control to the next Observable,
8637 * `concat` will error immediately as well. Observables that would be subscribed after
8638 * the one that emitted error, never will.
8640 * If you pass to `concat` the same Observable many times, its stream of values
8641 * will be "replayed" on every subscription, which means you can repeat given Observable
8642 * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
8643 * you can always use {@link repeat}.
8645 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8646 * var timer = Rx.Observable.interval(1000).take(4);
8647 * var sequence = Rx.Observable.range(1, 10);
8648 * var result = Rx.Observable.concat(timer, sequence);
8649 * result.subscribe(x => console.log(x));
8652 * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8655 * @example <caption>Concatenate an array of 3 Observables</caption>
8656 * var timer1 = Rx.Observable.interval(1000).take(10);
8657 * var timer2 = Rx.Observable.interval(2000).take(6);
8658 * var timer3 = Rx.Observable.interval(500).take(10);
8659 * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
8660 * result.subscribe(x => console.log(x));
8662 * // results in the following:
8663 * // (Prints to console sequentially)
8664 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8665 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8666 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8669 * @example <caption>Concatenate the same Observable to repeat it</caption>
8670 * const timer = Rx.Observable.interval(1000).take(2);
8672 * Rx.Observable.concat(timer, timer) // concating the same Observable!
8674 * value => console.log(value),
8676 * () => console.log('...and it is done!')
8684 * // "...and it is done!" also after 4s
8686 * @see {@link concatAll}
8687 * @see {@link concatMap}
8688 * @see {@link concatMapTo}
8690 * @param {ObservableInput} input1 An input Observable to concatenate with others.
8691 * @param {ObservableInput} input2 An input Observable to concatenate with others.
8692 * More than one input Observables may be given as argument.
8693 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8694 * Observable subscription on.
8695 * @return {Observable} All values of each passed Observable merged into a
8696 * single Observable, in order, in serial fashion.
8702 var observables = [];
8703 for (var _i = 0; _i < arguments.length; _i++) {
8704 observables[_i - 0] = arguments[_i];
8706 if (observables.length === 1 || (observables.length === 2 && isScheduler_1.isScheduler(observables[1]))) {
8707 return from_1.from(observables[0]);
8709 return concatAll_1.concatAll()(of_1.of.apply(void 0, observables));
8711 exports.concat = concat;
8713 },{"../operators/concatAll":159,"../util/isScheduler":224,"./from":105,"./of":109}],103:[function(require,module,exports){
8715 var DeferObservable_1 = require('./DeferObservable');
8716 exports.defer = DeferObservable_1.DeferObservable.create;
8718 },{"./DeferObservable":92}],104:[function(require,module,exports){
8720 var EmptyObservable_1 = require('./EmptyObservable');
8721 exports.empty = EmptyObservable_1.EmptyObservable.create;
8723 },{"./EmptyObservable":93}],105:[function(require,module,exports){
8725 var FromObservable_1 = require('./FromObservable');
8726 exports.from = FromObservable_1.FromObservable.create;
8728 },{"./FromObservable":96}],106:[function(require,module,exports){
8730 var FromEventObservable_1 = require('./FromEventObservable');
8731 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8733 },{"./FromEventObservable":95}],107:[function(require,module,exports){
8735 var PromiseObservable_1 = require('./PromiseObservable');
8736 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8738 },{"./PromiseObservable":98}],108:[function(require,module,exports){
8740 var merge_1 = require('../operator/merge');
8741 exports.merge = merge_1.mergeStatic;
8743 },{"../operator/merge":130}],109:[function(require,module,exports){
8745 var ArrayObservable_1 = require('./ArrayObservable');
8746 exports.of = ArrayObservable_1.ArrayObservable.of;
8748 },{"./ArrayObservable":90}],110:[function(require,module,exports){
8750 var ErrorObservable_1 = require('./ErrorObservable');
8751 exports._throw = ErrorObservable_1.ErrorObservable.create;
8753 },{"./ErrorObservable":94}],111:[function(require,module,exports){
8755 var TimerObservable_1 = require('./TimerObservable');
8756 exports.timer = TimerObservable_1.TimerObservable.create;
8758 },{"./TimerObservable":100}],112:[function(require,module,exports){
8760 var zip_1 = require('../operators/zip');
8761 exports.zip = zip_1.zipStatic;
8763 },{"../operators/zip":197}],113:[function(require,module,exports){
8765 var buffer_1 = require('../operators/buffer');
8767 * Buffers the source Observable values until `closingNotifier` emits.
8769 * <span class="informal">Collects values from the past as an array, and emits
8770 * that array only when another Observable emits.</span>
8772 * <img src="./img/buffer.png" width="100%">
8774 * Buffers the incoming Observable values until the given `closingNotifier`
8775 * Observable emits a value, at which point it emits the buffer on the output
8776 * Observable and starts a new buffer internally, awaiting the next time
8777 * `closingNotifier` emits.
8779 * @example <caption>On every click, emit array of most recent interval events</caption>
8780 * var clicks = Rx.Observable.fromEvent(document, 'click');
8781 * var interval = Rx.Observable.interval(1000);
8782 * var buffered = interval.buffer(clicks);
8783 * buffered.subscribe(x => console.log(x));
8785 * @see {@link bufferCount}
8786 * @see {@link bufferTime}
8787 * @see {@link bufferToggle}
8788 * @see {@link bufferWhen}
8789 * @see {@link window}
8791 * @param {Observable<any>} closingNotifier An Observable that signals the
8792 * buffer to be emitted on the output Observable.
8793 * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8798 function buffer(closingNotifier) {
8799 return buffer_1.buffer(closingNotifier)(this);
8801 exports.buffer = buffer;
8803 },{"../operators/buffer":153}],114:[function(require,module,exports){
8805 var bufferCount_1 = require('../operators/bufferCount');
8807 * Buffers the source Observable values until the size hits the maximum
8808 * `bufferSize` given.
8810 * <span class="informal">Collects values from the past as an array, and emits
8811 * that array only when its size reaches `bufferSize`.</span>
8813 * <img src="./img/bufferCount.png" width="100%">
8815 * Buffers a number of values from the source Observable by `bufferSize` then
8816 * emits the buffer and clears it, and starts a new buffer each
8817 * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8818 * `null`, then new buffers are started immediately at the start of the source
8819 * and when each buffer closes and is emitted.
8821 * @example <caption>Emit the last two click events as an array</caption>
8822 * var clicks = Rx.Observable.fromEvent(document, 'click');
8823 * var buffered = clicks.bufferCount(2);
8824 * buffered.subscribe(x => console.log(x));
8826 * @example <caption>On every click, emit the last two click events as an array</caption>
8827 * var clicks = Rx.Observable.fromEvent(document, 'click');
8828 * var buffered = clicks.bufferCount(2, 1);
8829 * buffered.subscribe(x => console.log(x));
8831 * @see {@link buffer}
8832 * @see {@link bufferTime}
8833 * @see {@link bufferToggle}
8834 * @see {@link bufferWhen}
8835 * @see {@link pairwise}
8836 * @see {@link windowCount}
8838 * @param {number} bufferSize The maximum size of the buffer emitted.
8839 * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8840 * For example if `startBufferEvery` is `2`, then a new buffer will be started
8841 * on every other value from the source. A new buffer is started at the
8842 * beginning of the source by default.
8843 * @return {Observable<T[]>} An Observable of arrays of buffered values.
8844 * @method bufferCount
8847 function bufferCount(bufferSize, startBufferEvery) {
8848 if (startBufferEvery === void 0) { startBufferEvery = null; }
8849 return bufferCount_1.bufferCount(bufferSize, startBufferEvery)(this);
8851 exports.bufferCount = bufferCount;
8853 },{"../operators/bufferCount":154}],115:[function(require,module,exports){
8855 var bufferWhen_1 = require('../operators/bufferWhen');
8857 * Buffers the source Observable values, using a factory function of closing
8858 * Observables to determine when to close, emit, and reset the buffer.
8860 * <span class="informal">Collects values from the past as an array. When it
8861 * starts collecting values, it calls a function that returns an Observable that
8862 * tells when to close the buffer and restart collecting.</span>
8864 * <img src="./img/bufferWhen.png" width="100%">
8866 * Opens a buffer immediately, then closes the buffer when the observable
8867 * returned by calling `closingSelector` function emits a value. When it closes
8868 * the buffer, it immediately opens a new buffer and repeats the process.
8870 * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8871 * var clicks = Rx.Observable.fromEvent(document, 'click');
8872 * var buffered = clicks.bufferWhen(() =>
8873 * Rx.Observable.interval(1000 + Math.random() * 4000)
8875 * buffered.subscribe(x => console.log(x));
8877 * @see {@link buffer}
8878 * @see {@link bufferCount}
8879 * @see {@link bufferTime}
8880 * @see {@link bufferToggle}
8881 * @see {@link windowWhen}
8883 * @param {function(): Observable} closingSelector A function that takes no
8884 * arguments and returns an Observable that signals buffer closure.
8885 * @return {Observable<T[]>} An observable of arrays of buffered values.
8886 * @method bufferWhen
8889 function bufferWhen(closingSelector) {
8890 return bufferWhen_1.bufferWhen(closingSelector)(this);
8892 exports.bufferWhen = bufferWhen;
8894 },{"../operators/bufferWhen":155}],116:[function(require,module,exports){
8896 var catchError_1 = require('../operators/catchError');
8898 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8900 * <img src="./img/catch.png" width="100%">
8902 * @example <caption>Continues with a different Observable when there's an error</caption>
8904 * Observable.of(1, 2, 3, 4, 5)
8911 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8912 * .subscribe(x => console.log(x));
8913 * // 1, 2, 3, I, II, III, IV, V
8915 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8917 * Observable.of(1, 2, 3, 4, 5)
8924 * .catch((err, caught) => caught)
8926 * .subscribe(x => console.log(x));
8927 * // 1, 2, 3, 1, 2, 3, ...
8929 * @example <caption>Throws a new error when the source Observable throws an error</caption>
8931 * Observable.of(1, 2, 3, 4, 5)
8939 * throw 'error in source. Details: ' + err;
8942 * x => console.log(x),
8943 * err => console.log(err)
8945 * // 1, 2, 3, error in source. Details: four!
8947 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8948 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8949 * is returned by the `selector` will be used to continue the observable chain.
8950 * @return {Observable} An observable that originates from either the source or the observable returned by the
8951 * catch `selector` function.
8956 function _catch(selector) {
8957 return catchError_1.catchError(selector)(this);
8959 exports._catch = _catch;
8961 },{"../operators/catchError":156}],117:[function(require,module,exports){
8963 var combineLatest_1 = require('../operators/combineLatest');
8964 /* tslint:enable:max-line-length */
8966 * Combines multiple Observables to create an Observable whose values are
8967 * calculated from the latest values of each of its input Observables.
8969 * <span class="informal">Whenever any input Observable emits a value, it
8970 * computes a formula using the latest values from all the inputs, then emits
8971 * the output of that formula.</span>
8973 * <img src="./img/combineLatest.png" width="100%">
8975 * `combineLatest` combines the values from this Observable with values from
8976 * Observables passed as arguments. This is done by subscribing to each
8977 * Observable, in order, and collecting an array of each of the most recent
8978 * values any time any of the input Observables emits, then either taking that
8979 * array and passing it as arguments to an optional `project` function and
8980 * emitting the return value of that, or just emitting the array of recent
8981 * values directly if there is no `project` function.
8983 * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
8984 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8985 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8986 * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
8987 * bmi.subscribe(x => console.log('BMI is ' + x));
8989 * // With output to console:
8990 * // BMI is 24.212293388429753
8991 * // BMI is 23.93948099205209
8992 * // BMI is 23.671253629592222
8994 * @see {@link combineAll}
8995 * @see {@link merge}
8996 * @see {@link withLatestFrom}
8998 * @param {ObservableInput} other An input Observable to combine with the source
8999 * Observable. More than one input Observables may be given as argument.
9000 * @param {function} [project] An optional function to project the values from
9001 * the combined latest values into a new value on the output Observable.
9002 * @return {Observable} An Observable of projected values from the most recent
9003 * values from each input Observable, or an array of the most recent values from
9004 * each input Observable.
9005 * @method combineLatest
9008 function combineLatest() {
9009 var observables = [];
9010 for (var _i = 0; _i < arguments.length; _i++) {
9011 observables[_i - 0] = arguments[_i];
9013 return combineLatest_1.combineLatest.apply(void 0, observables)(this);
9015 exports.combineLatest = combineLatest;
9017 },{"../operators/combineLatest":157}],118:[function(require,module,exports){
9019 var concat_1 = require('../operators/concat');
9020 /* tslint:enable:max-line-length */
9022 * Creates an output Observable which sequentially emits all values from every
9023 * given input Observable after the current Observable.
9025 * <span class="informal">Concatenates multiple Observables together by
9026 * sequentially emitting their values, one Observable after the other.</span>
9028 * <img src="./img/concat.png" width="100%">
9030 * Joins this Observable with multiple other Observables by subscribing to them
9031 * one at a time, starting with the source, and merging their results into the
9032 * output Observable. Will wait for each Observable to complete before moving
9035 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9036 * var timer = Rx.Observable.interval(1000).take(4);
9037 * var sequence = Rx.Observable.range(1, 10);
9038 * var result = timer.concat(sequence);
9039 * result.subscribe(x => console.log(x));
9042 * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9044 * @example <caption>Concatenate 3 Observables</caption>
9045 * var timer1 = Rx.Observable.interval(1000).take(10);
9046 * var timer2 = Rx.Observable.interval(2000).take(6);
9047 * var timer3 = Rx.Observable.interval(500).take(10);
9048 * var result = timer1.concat(timer2, timer3);
9049 * result.subscribe(x => console.log(x));
9051 * // results in the following:
9052 * // (Prints to console sequentially)
9053 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9054 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9055 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9057 * @see {@link concatAll}
9058 * @see {@link concatMap}
9059 * @see {@link concatMapTo}
9061 * @param {ObservableInput} other An input Observable to concatenate after the source
9062 * Observable. More than one input Observables may be given as argument.
9063 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9064 * Observable subscription on.
9065 * @return {Observable} All values of each passed Observable merged into a
9066 * single Observable, in order, in serial fashion.
9071 var observables = [];
9072 for (var _i = 0; _i < arguments.length; _i++) {
9073 observables[_i - 0] = arguments[_i];
9075 return concat_1.concat.apply(void 0, observables)(this);
9077 exports.concat = concat;
9079 },{"../operators/concat":158}],119:[function(require,module,exports){
9081 var async_1 = require('../scheduler/async');
9082 var debounceTime_1 = require('../operators/debounceTime');
9084 * Emits a value from the source Observable only after a particular time span
9085 * has passed without another source emission.
9087 * <span class="informal">It's like {@link delay}, but passes only the most
9088 * recent value from each burst of emissions.</span>
9090 * <img src="./img/debounceTime.png" width="100%">
9092 * `debounceTime` delays values emitted by the source Observable, but drops
9093 * previous pending delayed emissions if a new value arrives on the source
9094 * Observable. This operator keeps track of the most recent value from the
9095 * source Observable, and emits that only when `dueTime` enough time has passed
9096 * without any other value appearing on the source Observable. If a new value
9097 * appears before `dueTime` silence occurs, the previous value will be dropped
9098 * and will not be emitted on the output Observable.
9100 * This is a rate-limiting operator, because it is impossible for more than one
9101 * value to be emitted in any time window of duration `dueTime`, but it is also
9102 * a delay-like operator since output emissions do not occur at the same time as
9103 * they did on the source Observable. Optionally takes a {@link IScheduler} for
9106 * @example <caption>Emit the most recent click after a burst of clicks</caption>
9107 * var clicks = Rx.Observable.fromEvent(document, 'click');
9108 * var result = clicks.debounceTime(1000);
9109 * result.subscribe(x => console.log(x));
9111 * @see {@link auditTime}
9112 * @see {@link debounce}
9113 * @see {@link delay}
9114 * @see {@link sampleTime}
9115 * @see {@link throttleTime}
9117 * @param {number} dueTime The timeout duration in milliseconds (or the time
9118 * unit determined internally by the optional `scheduler`) for the window of
9119 * time required to wait for emission silence before emitting the most recent
9121 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
9122 * managing the timers that handle the timeout for each value.
9123 * @return {Observable} An Observable that delays the emissions of the source
9124 * Observable by the specified `dueTime`, and may drop some values if they occur
9126 * @method debounceTime
9129 function debounceTime(dueTime, scheduler) {
9130 if (scheduler === void 0) { scheduler = async_1.async; }
9131 return debounceTime_1.debounceTime(dueTime, scheduler)(this);
9133 exports.debounceTime = debounceTime;
9135 },{"../operators/debounceTime":160,"../scheduler/async":203}],120:[function(require,module,exports){
9137 var async_1 = require('../scheduler/async');
9138 var delay_1 = require('../operators/delay');
9140 * Delays the emission of items from the source Observable by a given timeout or
9141 * until a given Date.
9143 * <span class="informal">Time shifts each item by some specified amount of
9144 * milliseconds.</span>
9146 * <img src="./img/delay.png" width="100%">
9148 * If the delay argument is a Number, this operator time shifts the source
9149 * Observable by that amount of time expressed in milliseconds. The relative
9150 * time intervals between the values are preserved.
9152 * If the delay argument is a Date, this operator time shifts the start of the
9153 * Observable execution until the given date occurs.
9155 * @example <caption>Delay each click by one second</caption>
9156 * var clicks = Rx.Observable.fromEvent(document, 'click');
9157 * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9158 * delayedClicks.subscribe(x => console.log(x));
9160 * @example <caption>Delay all clicks until a future date happens</caption>
9161 * var clicks = Rx.Observable.fromEvent(document, 'click');
9162 * var date = new Date('March 15, 2050 12:00:00'); // in the future
9163 * var delayedClicks = clicks.delay(date); // click emitted only after that date
9164 * delayedClicks.subscribe(x => console.log(x));
9166 * @see {@link debounceTime}
9167 * @see {@link delayWhen}
9169 * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9170 * a `Date` until which the emission of the source items is delayed.
9171 * @param {Scheduler} [scheduler=async] The IScheduler to use for
9172 * managing the timers that handle the time-shift for each item.
9173 * @return {Observable} An Observable that delays the emissions of the source
9174 * Observable by the specified timeout or Date.
9178 function delay(delay, scheduler) {
9179 if (scheduler === void 0) { scheduler = async_1.async; }
9180 return delay_1.delay(delay, scheduler)(this);
9182 exports.delay = delay;
9184 },{"../operators/delay":161,"../scheduler/async":203}],121:[function(require,module,exports){
9186 var distinct_1 = require('../operators/distinct');
9188 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9190 * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9191 * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9192 * source observable directly with an equality check against previous values.
9194 * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9196 * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9197 * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9198 * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9199 * that the internal `Set` can be "flushed", basically clearing it of values.
9201 * @example <caption>A simple example with numbers</caption>
9202 * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9204 * .subscribe(x => console.log(x)); // 1, 2, 3, 4
9206 * @example <caption>An example using a keySelector function</caption>
9207 * interface Person {
9212 * Observable.of<Person>(
9213 * { age: 4, name: 'Foo'},
9214 * { age: 7, name: 'Bar'},
9215 * { age: 5, name: 'Foo'})
9216 * .distinct((p: Person) => p.name)
9217 * .subscribe(x => console.log(x));
9220 * // { age: 4, name: 'Foo' }
9221 * // { age: 7, name: 'Bar' }
9223 * @see {@link distinctUntilChanged}
9224 * @see {@link distinctUntilKeyChanged}
9226 * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9227 * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9228 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9232 function distinct(keySelector, flushes) {
9233 return distinct_1.distinct(keySelector, flushes)(this);
9235 exports.distinct = distinct;
9237 },{"../operators/distinct":162}],122:[function(require,module,exports){
9239 var distinctUntilChanged_1 = require('../operators/distinctUntilChanged');
9240 /* tslint:enable:max-line-length */
9242 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9244 * 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.
9246 * If a comparator function is not provided, an equality check is used by default.
9248 * @example <caption>A simple example with numbers</caption>
9249 * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9250 * .distinctUntilChanged()
9251 * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9253 * @example <caption>An example using a compare function</caption>
9254 * interface Person {
9259 * Observable.of<Person>(
9260 * { age: 4, name: 'Foo'},
9261 * { age: 7, name: 'Bar'},
9262 * { age: 5, name: 'Foo'})
9263 * { age: 6, name: 'Foo'})
9264 * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9265 * .subscribe(x => console.log(x));
9268 * // { age: 4, name: 'Foo' }
9269 * // { age: 7, name: 'Bar' }
9270 * // { age: 5, name: 'Foo' }
9272 * @see {@link distinct}
9273 * @see {@link distinctUntilKeyChanged}
9275 * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9276 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9277 * @method distinctUntilChanged
9280 function distinctUntilChanged(compare, keySelector) {
9281 return distinctUntilChanged_1.distinctUntilChanged(compare, keySelector)(this);
9283 exports.distinctUntilChanged = distinctUntilChanged;
9285 },{"../operators/distinctUntilChanged":163}],123:[function(require,module,exports){
9287 var tap_1 = require('../operators/tap');
9288 /* tslint:enable:max-line-length */
9290 * Perform a side effect for every emission on the source Observable, but return
9291 * an Observable that is identical to the source.
9293 * <span class="informal">Intercepts each emission on the source and runs a
9294 * function, but returns an output which is identical to the source as long as errors don't occur.</span>
9296 * <img src="./img/do.png" width="100%">
9298 * Returns a mirrored Observable of the source Observable, but modified so that
9299 * the provided Observer is called to perform a side effect for every value,
9300 * error, and completion emitted by the source. Any errors that are thrown in
9301 * the aforementioned Observer or handlers are safely sent down the error path
9302 * of the output Observable.
9304 * This operator is useful for debugging your Observables for the correct values
9305 * or performing other side effects.
9307 * Note: this is different to a `subscribe` on the Observable. If the Observable
9308 * returned by `do` is not subscribed, the side effects specified by the
9309 * Observer will never happen. `do` therefore simply spies on existing
9310 * execution, it does not trigger an execution to happen like `subscribe` does.
9312 * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
9313 * var clicks = Rx.Observable.fromEvent(document, 'click');
9314 * var positions = clicks
9315 * .do(ev => console.log(ev))
9316 * .map(ev => ev.clientX);
9317 * positions.subscribe(x => console.log(x));
9320 * @see {@link subscribe}
9322 * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9323 * callback for `next`.
9324 * @param {function} [error] Callback for errors in the source.
9325 * @param {function} [complete] Callback for the completion of the source.
9326 * @return {Observable} An Observable identical to the source, but runs the
9327 * specified Observer or callback(s) for each item.
9332 function _do(nextOrObserver, error, complete) {
9333 return tap_1.tap(nextOrObserver, error, complete)(this);
9337 },{"../operators/tap":192}],124:[function(require,module,exports){
9339 var expand_1 = require('../operators/expand');
9340 /* tslint:enable:max-line-length */
9342 * Recursively projects each source value to an Observable which is merged in
9343 * the output Observable.
9345 * <span class="informal">It's similar to {@link mergeMap}, but applies the
9346 * projection function to every source value as well as every output value.
9347 * It's recursive.</span>
9349 * <img src="./img/expand.png" width="100%">
9351 * Returns an Observable that emits items based on applying a function that you
9352 * supply to each item emitted by the source Observable, where that function
9353 * returns an Observable, and then merging those resulting Observables and
9354 * emitting the results of this merger. *Expand* will re-emit on the output
9355 * Observable every source value. Then, each output value is given to the
9356 * `project` function which returns an inner Observable to be merged on the
9357 * output Observable. Those output values resulting from the projection are also
9358 * given to the `project` function to produce new output values. This is how
9359 * *expand* behaves recursively.
9361 * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9362 * var clicks = Rx.Observable.fromEvent(document, 'click');
9363 * var powersOfTwo = clicks
9365 * .expand(x => Rx.Observable.of(2 * x).delay(1000))
9367 * powersOfTwo.subscribe(x => console.log(x));
9369 * @see {@link mergeMap}
9370 * @see {@link mergeScan}
9372 * @param {function(value: T, index: number) => Observable} project A function
9373 * that, when applied to an item emitted by the source or the output Observable,
9374 * returns an Observable.
9375 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9376 * Observables being subscribed to concurrently.
9377 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9378 * each projected inner Observable.
9379 * @return {Observable} An Observable that emits the source values and also
9380 * result of applying the projection function to each value emitted on the
9381 * output Observable and and merging the results of the Observables obtained
9382 * from this transformation.
9386 function expand(project, concurrent, scheduler) {
9387 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9388 if (scheduler === void 0) { scheduler = undefined; }
9389 concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9390 return expand_1.expand(project, concurrent, scheduler)(this);
9392 exports.expand = expand;
9394 },{"../operators/expand":164}],125:[function(require,module,exports){
9396 var filter_1 = require('../operators/filter');
9397 /* tslint:enable:max-line-length */
9399 * Filter items emitted by the source Observable by only emitting those that
9400 * satisfy a specified predicate.
9402 * <span class="informal">Like
9403 * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
9404 * it only emits a value from the source if it passes a criterion function.</span>
9406 * <img src="./img/filter.png" width="100%">
9408 * Similar to the well-known `Array.prototype.filter` method, this operator
9409 * takes values from the source Observable, passes them through a `predicate`
9410 * function and only emits those values that yielded `true`.
9412 * @example <caption>Emit only click events whose target was a DIV element</caption>
9413 * var clicks = Rx.Observable.fromEvent(document, 'click');
9414 * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
9415 * clicksOnDivs.subscribe(x => console.log(x));
9417 * @see {@link distinct}
9418 * @see {@link distinctUntilChanged}
9419 * @see {@link distinctUntilKeyChanged}
9420 * @see {@link ignoreElements}
9421 * @see {@link partition}
9424 * @param {function(value: T, index: number): boolean} predicate A function that
9425 * evaluates each value emitted by the source Observable. If it returns `true`,
9426 * the value is emitted, if `false` the value is not passed to the output
9427 * Observable. The `index` parameter is the number `i` for the i-th source
9428 * emission that has happened since the subscription, starting from the number
9430 * @param {any} [thisArg] An optional argument to determine the value of `this`
9431 * in the `predicate` function.
9432 * @return {Observable} An Observable of values from the source that were
9433 * allowed by the `predicate` function.
9437 function filter(predicate, thisArg) {
9438 return filter_1.filter(predicate, thisArg)(this);
9440 exports.filter = filter;
9442 },{"../operators/filter":165}],126:[function(require,module,exports){
9444 var finalize_1 = require('../operators/finalize');
9446 * Returns an Observable that mirrors the source Observable, but will call a specified function when
9447 * the source terminates on complete or error.
9448 * @param {function} callback Function to be called when source terminates.
9449 * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
9453 function _finally(callback) {
9454 return finalize_1.finalize(callback)(this);
9456 exports._finally = _finally;
9458 },{"../operators/finalize":166}],127:[function(require,module,exports){
9460 var first_1 = require('../operators/first');
9462 * Emits only the first value (or the first value that meets some condition)
9463 * emitted by the source Observable.
9465 * <span class="informal">Emits only the first value. Or emits only the first
9466 * value that passes some test.</span>
9468 * <img src="./img/first.png" width="100%">
9470 * If called with no arguments, `first` emits the first value of the source
9471 * Observable, then completes. If called with a `predicate` function, `first`
9472 * emits the first value of the source that matches the specified condition. It
9473 * may also take a `resultSelector` function to produce the output value from
9474 * the input value, and a `defaultValue` to emit in case the source completes
9475 * before it is able to emit a valid value. Throws an error if `defaultValue`
9476 * was not provided and a matching element is not found.
9478 * @example <caption>Emit only the first click that happens on the DOM</caption>
9479 * var clicks = Rx.Observable.fromEvent(document, 'click');
9480 * var result = clicks.first();
9481 * result.subscribe(x => console.log(x));
9483 * @example <caption>Emits the first click that happens on a DIV</caption>
9484 * var clicks = Rx.Observable.fromEvent(document, 'click');
9485 * var result = clicks.first(ev => ev.target.tagName === 'DIV');
9486 * result.subscribe(x => console.log(x));
9488 * @see {@link filter}
9492 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9493 * callback if the Observable completes before any `next` notification was sent.
9495 * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
9496 * An optional function called with each item to test for condition matching.
9497 * @param {function(value: T, index: number): R} [resultSelector] A function to
9498 * produce the value on the output Observable based on the values
9499 * and the indices of the source Observable. The arguments passed to this
9501 * - `value`: the value that was emitted on the source.
9502 * - `index`: the "index" of the value from the source.
9503 * @param {R} [defaultValue] The default value emitted in case no valid value
9504 * was found on the source.
9505 * @return {Observable<T|R>} An Observable of the first item that matches the
9510 function first(predicate, resultSelector, defaultValue) {
9511 return first_1.first(predicate, resultSelector, defaultValue)(this);
9513 exports.first = first;
9515 },{"../operators/first":167}],128:[function(require,module,exports){
9517 var last_1 = require('../operators/last');
9518 /* tslint:enable:max-line-length */
9520 * Returns an Observable that emits only the last item emitted by the source Observable.
9521 * It optionally takes a predicate function as a parameter, in which case, rather than emitting
9522 * the last item from the source Observable, the resulting Observable will emit the last item
9523 * from the source Observable that satisfies the predicate.
9525 * <img src="./img/last.png" width="100%">
9527 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9528 * callback if the Observable completes before any `next` notification was sent.
9529 * @param {function} predicate - The condition any source emitted item has to satisfy.
9530 * @return {Observable} An Observable that emits only the last item satisfying the given condition
9531 * from the source, or an NoSuchElementException if no such items are emitted.
9532 * @throws - Throws if no items that match the predicate are emitted by the source Observable.
9536 function last(predicate, resultSelector, defaultValue) {
9537 return last_1.last(predicate, resultSelector, defaultValue)(this);
9539 exports.last = last;
9541 },{"../operators/last":168}],129:[function(require,module,exports){
9543 var map_1 = require('../operators/map');
9545 * Applies a given `project` function to each value emitted by the source
9546 * Observable, and emits the resulting values as an Observable.
9548 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
9549 * it passes each source value through a transformation function to get
9550 * corresponding output values.</span>
9552 * <img src="./img/map.png" width="100%">
9554 * Similar to the well known `Array.prototype.map` function, this operator
9555 * applies a projection to each value and emits that projection in the output
9558 * @example <caption>Map every click to the clientX position of that click</caption>
9559 * var clicks = Rx.Observable.fromEvent(document, 'click');
9560 * var positions = clicks.map(ev => ev.clientX);
9561 * positions.subscribe(x => console.log(x));
9563 * @see {@link mapTo}
9564 * @see {@link pluck}
9566 * @param {function(value: T, index: number): R} project The function to apply
9567 * to each `value` emitted by the source Observable. The `index` parameter is
9568 * the number `i` for the i-th emission that has happened since the
9569 * subscription, starting from the number `0`.
9570 * @param {any} [thisArg] An optional argument to define what `this` is in the
9571 * `project` function.
9572 * @return {Observable<R>} An Observable that emits the values from the source
9573 * Observable transformed by the given `project` function.
9577 function map(project, thisArg) {
9578 return map_1.map(project, thisArg)(this);
9582 },{"../operators/map":169}],130:[function(require,module,exports){
9584 var merge_1 = require('../operators/merge');
9585 var merge_2 = require('../operators/merge');
9586 exports.mergeStatic = merge_2.mergeStatic;
9587 /* tslint:enable:max-line-length */
9589 * Creates an output Observable which concurrently emits all values from every
9590 * given input Observable.
9592 * <span class="informal">Flattens multiple Observables together by blending
9593 * their values into one Observable.</span>
9595 * <img src="./img/merge.png" width="100%">
9597 * `merge` subscribes to each given input Observable (either the source or an
9598 * Observable given as argument), and simply forwards (without doing any
9599 * transformation) all the values from all the input Observables to the output
9600 * Observable. The output Observable only completes once all input Observables
9601 * have completed. Any error delivered by an input Observable will be immediately
9602 * emitted on the output Observable.
9604 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
9605 * var clicks = Rx.Observable.fromEvent(document, 'click');
9606 * var timer = Rx.Observable.interval(1000);
9607 * var clicksOrTimer = clicks.merge(timer);
9608 * clicksOrTimer.subscribe(x => console.log(x));
9610 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
9611 * var timer1 = Rx.Observable.interval(1000).take(10);
9612 * var timer2 = Rx.Observable.interval(2000).take(6);
9613 * var timer3 = Rx.Observable.interval(500).take(10);
9614 * var concurrent = 2; // the argument
9615 * var merged = timer1.merge(timer2, timer3, concurrent);
9616 * merged.subscribe(x => console.log(x));
9618 * @see {@link mergeAll}
9619 * @see {@link mergeMap}
9620 * @see {@link mergeMapTo}
9621 * @see {@link mergeScan}
9623 * @param {ObservableInput} other An input Observable to merge with the source
9624 * Observable. More than one input Observables may be given as argument.
9625 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9626 * Observables being subscribed to concurrently.
9627 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
9628 * concurrency of input Observables.
9629 * @return {Observable} An Observable that emits items that are the result of
9630 * every input Observable.
9635 var observables = [];
9636 for (var _i = 0; _i < arguments.length; _i++) {
9637 observables[_i - 0] = arguments[_i];
9639 return merge_1.merge.apply(void 0, observables)(this);
9641 exports.merge = merge;
9643 },{"../operators/merge":170}],131:[function(require,module,exports){
9645 var mergeAll_1 = require('../operators/mergeAll');
9647 * Converts a higher-order Observable into a first-order Observable which
9648 * concurrently delivers all values that are emitted on the inner Observables.
9650 * <span class="informal">Flattens an Observable-of-Observables.</span>
9652 * <img src="./img/mergeAll.png" width="100%">
9654 * `mergeAll` subscribes to an Observable that emits Observables, also known as
9655 * a higher-order Observable. Each time it observes one of these emitted inner
9656 * Observables, it subscribes to that and delivers all the values from the
9657 * inner Observable on the output Observable. The output Observable only
9658 * completes once all inner Observables have completed. Any error delivered by
9659 * a inner Observable will be immediately emitted on the output Observable.
9661 * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
9662 * var clicks = Rx.Observable.fromEvent(document, 'click');
9663 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
9664 * var firstOrder = higherOrder.mergeAll();
9665 * firstOrder.subscribe(x => console.log(x));
9667 * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
9668 * var clicks = Rx.Observable.fromEvent(document, 'click');
9669 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
9670 * var firstOrder = higherOrder.mergeAll(2);
9671 * firstOrder.subscribe(x => console.log(x));
9673 * @see {@link combineAll}
9674 * @see {@link concatAll}
9675 * @see {@link exhaust}
9676 * @see {@link merge}
9677 * @see {@link mergeMap}
9678 * @see {@link mergeMapTo}
9679 * @see {@link mergeScan}
9680 * @see {@link switch}
9681 * @see {@link zipAll}
9683 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
9684 * Observables being subscribed to concurrently.
9685 * @return {Observable} An Observable that emits values coming from all the
9686 * inner Observables emitted by the source Observable.
9690 function mergeAll(concurrent) {
9691 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9692 return mergeAll_1.mergeAll(concurrent)(this);
9694 exports.mergeAll = mergeAll;
9696 },{"../operators/mergeAll":171}],132:[function(require,module,exports){
9698 var mergeMap_1 = require('../operators/mergeMap');
9699 /* tslint:enable:max-line-length */
9701 * Projects each source value to an Observable which is merged in the output
9704 * <span class="informal">Maps each value to an Observable, then flattens all of
9705 * these inner Observables using {@link mergeAll}.</span>
9707 * <img src="./img/mergeMap.png" width="100%">
9709 * Returns an Observable that emits items based on applying a function that you
9710 * supply to each item emitted by the source Observable, where that function
9711 * returns an Observable, and then merging those resulting Observables and
9712 * emitting the results of this merger.
9714 * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
9715 * var letters = Rx.Observable.of('a', 'b', 'c');
9716 * var result = letters.mergeMap(x =>
9717 * Rx.Observable.interval(1000).map(i => x+i)
9719 * result.subscribe(x => console.log(x));
9721 * // Results in the following:
9728 * // continues to list a,b,c with respective ascending integers
9730 * @see {@link concatMap}
9731 * @see {@link exhaustMap}
9732 * @see {@link merge}
9733 * @see {@link mergeAll}
9734 * @see {@link mergeMapTo}
9735 * @see {@link mergeScan}
9736 * @see {@link switchMap}
9738 * @param {function(value: T, ?index: number): ObservableInput} project A function
9739 * that, when applied to an item emitted by the source Observable, returns an
9741 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
9742 * A function to produce the value on the output Observable based on the values
9743 * and the indices of the source (outer) emission and the inner Observable
9744 * emission. The arguments passed to this function are:
9745 * - `outerValue`: the value that came from the source
9746 * - `innerValue`: the value that came from the projected Observable
9747 * - `outerIndex`: the "index" of the value that came from the source
9748 * - `innerIndex`: the "index" of the value from the projected Observable
9749 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9750 * Observables being subscribed to concurrently.
9751 * @return {Observable} An Observable that emits the result of applying the
9752 * projection function (and the optional `resultSelector`) to each item emitted
9753 * by the source Observable and merging the results of the Observables obtained
9754 * from this transformation.
9758 function mergeMap(project, resultSelector, concurrent) {
9759 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9760 return mergeMap_1.mergeMap(project, resultSelector, concurrent)(this);
9762 exports.mergeMap = mergeMap;
9764 },{"../operators/mergeMap":172}],133:[function(require,module,exports){
9766 var pairwise_1 = require('../operators/pairwise');
9768 * Groups pairs of consecutive emissions together and emits them as an array of
9771 * <span class="informal">Puts the current value and previous value together as
9772 * an array, and emits that.</span>
9774 * <img src="./img/pairwise.png" width="100%">
9776 * The Nth emission from the source Observable will cause the output Observable
9777 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
9778 * pair. For this reason, `pairwise` emits on the second and subsequent
9779 * emissions from the source Observable, but not on the first emission, because
9780 * there is no previous value in that case.
9782 * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
9783 * var clicks = Rx.Observable.fromEvent(document, 'click');
9784 * var pairs = clicks.pairwise();
9785 * var distance = pairs.map(pair => {
9786 * var x0 = pair[0].clientX;
9787 * var y0 = pair[0].clientY;
9788 * var x1 = pair[1].clientX;
9789 * var y1 = pair[1].clientY;
9790 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
9792 * distance.subscribe(x => console.log(x));
9794 * @see {@link buffer}
9795 * @see {@link bufferCount}
9797 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
9798 * consecutive values from the source Observable.
9802 function pairwise() {
9803 return pairwise_1.pairwise()(this);
9805 exports.pairwise = pairwise;
9807 },{"../operators/pairwise":175}],134:[function(require,module,exports){
9809 var pluck_1 = require('../operators/pluck');
9811 * Maps each source value (an object) to its specified nested property.
9813 * <span class="informal">Like {@link map}, but meant only for picking one of
9814 * the nested properties of every emitted object.</span>
9816 * <img src="./img/pluck.png" width="100%">
9818 * Given a list of strings describing a path to an object property, retrieves
9819 * the value of a specified nested property from all values in the source
9820 * Observable. If a property can't be resolved, it will return `undefined` for
9823 * @example <caption>Map every click to the tagName of the clicked target element</caption>
9824 * var clicks = Rx.Observable.fromEvent(document, 'click');
9825 * var tagNames = clicks.pluck('target', 'tagName');
9826 * tagNames.subscribe(x => console.log(x));
9830 * @param {...string} properties The nested properties to pluck from each source
9831 * value (an object).
9832 * @return {Observable} A new Observable of property values from the source values.
9837 var properties = [];
9838 for (var _i = 0; _i < arguments.length; _i++) {
9839 properties[_i - 0] = arguments[_i];
9841 return pluck_1.pluck.apply(void 0, properties)(this);
9843 exports.pluck = pluck;
9845 },{"../operators/pluck":176}],135:[function(require,module,exports){
9847 var publish_1 = require('../operators/publish');
9848 /* tslint:enable:max-line-length */
9850 * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
9851 * before it begins emitting items to those Observers that have subscribed to it.
9853 * <img src="./img/publish.png" width="100%">
9855 * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
9856 * as needed, without causing multiple subscriptions to the source sequence.
9857 * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
9858 * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
9862 function publish(selector) {
9863 return publish_1.publish(selector)(this);
9865 exports.publish = publish;
9867 },{"../operators/publish":177}],136:[function(require,module,exports){
9869 var publishReplay_1 = require('../operators/publishReplay');
9870 /* tslint:enable:max-line-length */
9874 * @param selectorOrScheduler
9876 * @return {Observable<T> | ConnectableObservable<T>}
9877 * @method publishReplay
9880 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
9881 return publishReplay_1.publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler)(this);
9883 exports.publishReplay = publishReplay;
9885 },{"../operators/publishReplay":178}],137:[function(require,module,exports){
9887 var retry_1 = require('../operators/retry');
9889 * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
9890 * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
9891 * as a number parameter) rather than propagating the `error` call.
9893 * <img src="./img/retry.png" width="100%">
9895 * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
9896 * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
9897 * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
9898 * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
9899 * @param {number} count - Number of retry attempts before failing.
9900 * @return {Observable} The source Observable modified with the retry logic.
9904 function retry(count) {
9905 if (count === void 0) { count = -1; }
9906 return retry_1.retry(count)(this);
9908 exports.retry = retry;
9910 },{"../operators/retry":180}],138:[function(require,module,exports){
9912 var sample_1 = require('../operators/sample');
9914 * Emits the most recently emitted value from the source Observable whenever
9915 * another Observable, the `notifier`, emits.
9917 * <span class="informal">It's like {@link sampleTime}, but samples whenever
9918 * the `notifier` Observable emits something.</span>
9920 * <img src="./img/sample.png" width="100%">
9922 * Whenever the `notifier` Observable emits a value or completes, `sample`
9923 * looks at the source Observable and emits whichever value it has most recently
9924 * emitted since the previous sampling, unless the source has not emitted
9925 * anything since the previous sampling. The `notifier` is subscribed to as soon
9926 * as the output Observable is subscribed.
9928 * @example <caption>On every click, sample the most recent "seconds" timer</caption>
9929 * var seconds = Rx.Observable.interval(1000);
9930 * var clicks = Rx.Observable.fromEvent(document, 'click');
9931 * var result = seconds.sample(clicks);
9932 * result.subscribe(x => console.log(x));
9934 * @see {@link audit}
9935 * @see {@link debounce}
9936 * @see {@link sampleTime}
9937 * @see {@link throttle}
9939 * @param {Observable<any>} notifier The Observable to use for sampling the
9940 * source Observable.
9941 * @return {Observable<T>} An Observable that emits the results of sampling the
9942 * values emitted by the source Observable whenever the notifier Observable
9943 * emits value or completes.
9947 function sample(notifier) {
9948 return sample_1.sample(notifier)(this);
9950 exports.sample = sample;
9952 },{"../operators/sample":181}],139:[function(require,module,exports){
9954 var scan_1 = require('../operators/scan');
9955 /* tslint:enable:max-line-length */
9957 * Applies an accumulator function over the source Observable, and returns each
9958 * intermediate result, with an optional seed value.
9960 * <span class="informal">It's like {@link reduce}, but emits the current
9961 * accumulation whenever the source emits a value.</span>
9963 * <img src="./img/scan.png" width="100%">
9965 * Combines together all values emitted on the source, using an accumulator
9966 * function that knows how to join a new source value into the accumulation from
9967 * the past. Is similar to {@link reduce}, but emits the intermediate
9970 * Returns an Observable that applies a specified `accumulator` function to each
9971 * item emitted by the source Observable. If a `seed` value is specified, then
9972 * that value will be used as the initial value for the accumulator. If no seed
9973 * value is specified, the first item of the source is used as the seed.
9975 * @example <caption>Count the number of click events</caption>
9976 * var clicks = Rx.Observable.fromEvent(document, 'click');
9977 * var ones = clicks.mapTo(1);
9979 * var count = ones.scan((acc, one) => acc + one, seed);
9980 * count.subscribe(x => console.log(x));
9982 * @see {@link expand}
9983 * @see {@link mergeScan}
9984 * @see {@link reduce}
9986 * @param {function(acc: R, value: T, index: number): R} accumulator
9987 * The accumulator function called on each source value.
9988 * @param {T|R} [seed] The initial accumulation value.
9989 * @return {Observable<R>} An observable of the accumulated values.
9993 function scan(accumulator, seed) {
9994 if (arguments.length >= 2) {
9995 return scan_1.scan(accumulator, seed)(this);
9997 return scan_1.scan(accumulator)(this);
9999 exports.scan = scan;
10001 },{"../operators/scan":182}],140:[function(require,module,exports){
10003 var share_1 = require('../operators/share');
10005 * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
10006 * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
10007 * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
10009 * This behaves similarly to .publish().refCount(), with a behavior difference when the source observable emits complete.
10010 * .publish().refCount() will not resubscribe to the original source, however .share() will resubscribe to the original source.
10011 * Observable.of("test").publish().refCount() will not re-emit "test" on new subscriptions, Observable.of("test").share() will
10012 * re-emit "test" to new subscriptions.
10014 * <img src="./img/share.png" width="100%">
10016 * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
10018 * @owner Observable
10021 return share_1.share()(this);
10023 exports.share = share;
10026 },{"../operators/share":183}],141:[function(require,module,exports){
10028 var skip_1 = require('../operators/skip');
10030 * Returns an Observable that skips the first `count` items emitted by the source Observable.
10032 * <img src="./img/skip.png" width="100%">
10034 * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
10035 * @return {Observable} An Observable that skips values emitted by the source Observable.
10038 * @owner Observable
10040 function skip(count) {
10041 return skip_1.skip(count)(this);
10043 exports.skip = skip;
10045 },{"../operators/skip":184}],142:[function(require,module,exports){
10047 var skipUntil_1 = require('../operators/skipUntil');
10049 * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
10051 * <img src="./img/skipUntil.png" width="100%">
10053 * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
10054 * be mirrored by the resulting Observable.
10055 * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
10056 * an item, then emits the remaining items.
10057 * @method skipUntil
10058 * @owner Observable
10060 function skipUntil(notifier) {
10061 return skipUntil_1.skipUntil(notifier)(this);
10063 exports.skipUntil = skipUntil;
10065 },{"../operators/skipUntil":185}],143:[function(require,module,exports){
10067 var skipWhile_1 = require('../operators/skipWhile');
10069 * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
10070 * true, but emits all further source items as soon as the condition becomes false.
10072 * <img src="./img/skipWhile.png" width="100%">
10074 * @param {Function} predicate - A function to test each item emitted from the source Observable.
10075 * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
10076 * specified predicate becomes false.
10077 * @method skipWhile
10078 * @owner Observable
10080 function skipWhile(predicate) {
10081 return skipWhile_1.skipWhile(predicate)(this);
10083 exports.skipWhile = skipWhile;
10085 },{"../operators/skipWhile":186}],144:[function(require,module,exports){
10087 var startWith_1 = require('../operators/startWith');
10088 /* tslint:enable:max-line-length */
10090 * Returns an Observable that emits the items you specify as arguments before it begins to emit
10091 * items emitted by the source Observable.
10093 * <img src="./img/startWith.png" width="100%">
10095 * @param {...T} values - Items you want the modified Observable to emit first.
10096 * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
10097 * the emissions of the `next` notifications.
10098 * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
10099 * emitted by the source Observable.
10100 * @method startWith
10101 * @owner Observable
10103 function startWith() {
10105 for (var _i = 0; _i < arguments.length; _i++) {
10106 array[_i - 0] = arguments[_i];
10108 return startWith_1.startWith.apply(void 0, array)(this);
10110 exports.startWith = startWith;
10112 },{"../operators/startWith":187}],145:[function(require,module,exports){
10114 var switchMap_1 = require('../operators/switchMap');
10115 /* tslint:enable:max-line-length */
10117 * Projects each source value to an Observable which is merged in the output
10118 * Observable, emitting values only from the most recently projected Observable.
10120 * <span class="informal">Maps each value to an Observable, then flattens all of
10121 * these inner Observables using {@link switch}.</span>
10123 * <img src="./img/switchMap.png" width="100%">
10125 * Returns an Observable that emits items based on applying a function that you
10126 * supply to each item emitted by the source Observable, where that function
10127 * returns an (so-called "inner") Observable. Each time it observes one of these
10128 * inner Observables, the output Observable begins emitting the items emitted by
10129 * that inner Observable. When a new inner Observable is emitted, `switchMap`
10130 * stops emitting items from the earlier-emitted inner Observable and begins
10131 * emitting items from the new one. It continues to behave like this for
10132 * subsequent inner Observables.
10134 * @example <caption>Rerun an interval Observable on every click event</caption>
10135 * var clicks = Rx.Observable.fromEvent(document, 'click');
10136 * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
10137 * result.subscribe(x => console.log(x));
10139 * @see {@link concatMap}
10140 * @see {@link exhaustMap}
10141 * @see {@link mergeMap}
10142 * @see {@link switch}
10143 * @see {@link switchMapTo}
10145 * @param {function(value: T, ?index: number): ObservableInput} project A function
10146 * that, when applied to an item emitted by the source Observable, returns an
10148 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10149 * A function to produce the value on the output Observable based on the values
10150 * and the indices of the source (outer) emission and the inner Observable
10151 * emission. The arguments passed to this function are:
10152 * - `outerValue`: the value that came from the source
10153 * - `innerValue`: the value that came from the projected Observable
10154 * - `outerIndex`: the "index" of the value that came from the source
10155 * - `innerIndex`: the "index" of the value from the projected Observable
10156 * @return {Observable} An Observable that emits the result of applying the
10157 * projection function (and the optional `resultSelector`) to each item emitted
10158 * by the source Observable and taking only the values from the most recently
10159 * projected inner Observable.
10160 * @method switchMap
10161 * @owner Observable
10163 function switchMap(project, resultSelector) {
10164 return switchMap_1.switchMap(project, resultSelector)(this);
10166 exports.switchMap = switchMap;
10168 },{"../operators/switchMap":188}],146:[function(require,module,exports){
10170 var take_1 = require('../operators/take');
10172 * Emits only the first `count` values emitted by the source Observable.
10174 * <span class="informal">Takes the first `count` values from the source, then
10175 * completes.</span>
10177 * <img src="./img/take.png" width="100%">
10179 * `take` returns an Observable that emits only the first `count` values emitted
10180 * by the source Observable. If the source emits fewer than `count` values then
10181 * all of its values are emitted. After that, it completes, regardless if the
10182 * source completes.
10184 * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
10185 * var interval = Rx.Observable.interval(1000);
10186 * var five = interval.take(5);
10187 * five.subscribe(x => console.log(x));
10189 * @see {@link takeLast}
10190 * @see {@link takeUntil}
10191 * @see {@link takeWhile}
10192 * @see {@link skip}
10194 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
10195 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
10197 * @param {number} count The maximum number of `next` values to emit.
10198 * @return {Observable<T>} An Observable that emits only the first `count`
10199 * values emitted by the source Observable, or all of the values from the source
10200 * if the source emits fewer than `count` values.
10202 * @owner Observable
10204 function take(count) {
10205 return take_1.take(count)(this);
10207 exports.take = take;
10209 },{"../operators/take":189}],147:[function(require,module,exports){
10211 var takeUntil_1 = require('../operators/takeUntil');
10213 * Emits the values emitted by the source Observable until a `notifier`
10214 * Observable emits a value.
10216 * <span class="informal">Lets values pass until a second Observable,
10217 * `notifier`, emits something. Then, it completes.</span>
10219 * <img src="./img/takeUntil.png" width="100%">
10221 * `takeUntil` subscribes and begins mirroring the source Observable. It also
10222 * monitors a second Observable, `notifier` that you provide. If the `notifier`
10223 * emits a value, the output Observable stops mirroring the source Observable
10226 * @example <caption>Tick every second until the first click happens</caption>
10227 * var interval = Rx.Observable.interval(1000);
10228 * var clicks = Rx.Observable.fromEvent(document, 'click');
10229 * var result = interval.takeUntil(clicks);
10230 * result.subscribe(x => console.log(x));
10232 * @see {@link take}
10233 * @see {@link takeLast}
10234 * @see {@link takeWhile}
10235 * @see {@link skip}
10237 * @param {Observable} notifier The Observable whose first emitted value will
10238 * cause the output Observable of `takeUntil` to stop emitting values from the
10239 * source Observable.
10240 * @return {Observable<T>} An Observable that emits the values from the source
10241 * Observable until such time as `notifier` emits its first value.
10242 * @method takeUntil
10243 * @owner Observable
10245 function takeUntil(notifier) {
10246 return takeUntil_1.takeUntil(notifier)(this);
10248 exports.takeUntil = takeUntil;
10250 },{"../operators/takeUntil":190}],148:[function(require,module,exports){
10252 var takeWhile_1 = require('../operators/takeWhile');
10254 * Emits values emitted by the source Observable so long as each value satisfies
10255 * the given `predicate`, and then completes as soon as this `predicate` is not
10258 * <span class="informal">Takes values from the source only while they pass the
10259 * condition given. When the first value does not satisfy, it completes.</span>
10261 * <img src="./img/takeWhile.png" width="100%">
10263 * `takeWhile` subscribes and begins mirroring the source Observable. Each value
10264 * emitted on the source is given to the `predicate` function which returns a
10265 * boolean, representing a condition to be satisfied by the source values. The
10266 * output Observable emits the source values until such time as the `predicate`
10267 * returns false, at which point `takeWhile` stops mirroring the source
10268 * Observable and completes the output Observable.
10270 * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
10271 * var clicks = Rx.Observable.fromEvent(document, 'click');
10272 * var result = clicks.takeWhile(ev => ev.clientX > 200);
10273 * result.subscribe(x => console.log(x));
10275 * @see {@link take}
10276 * @see {@link takeLast}
10277 * @see {@link takeUntil}
10278 * @see {@link skip}
10280 * @param {function(value: T, index: number): boolean} predicate A function that
10281 * evaluates a value emitted by the source Observable and returns a boolean.
10282 * Also takes the (zero-based) index as the second argument.
10283 * @return {Observable<T>} An Observable that emits the values from the source
10284 * Observable so long as each value satisfies the condition defined by the
10285 * `predicate`, then completes.
10286 * @method takeWhile
10287 * @owner Observable
10289 function takeWhile(predicate) {
10290 return takeWhile_1.takeWhile(predicate)(this);
10292 exports.takeWhile = takeWhile;
10294 },{"../operators/takeWhile":191}],149:[function(require,module,exports){
10296 var async_1 = require('../scheduler/async');
10297 var throttle_1 = require('../operators/throttle');
10298 var throttleTime_1 = require('../operators/throttleTime');
10300 * Emits a value from the source Observable, then ignores subsequent source
10301 * values for `duration` milliseconds, then repeats this process.
10303 * <span class="informal">Lets a value pass, then ignores source values for the
10304 * next `duration` milliseconds.</span>
10306 * <img src="./img/throttleTime.png" width="100%">
10308 * `throttleTime` emits the source Observable values on the output Observable
10309 * when its internal timer is disabled, and ignores source values when the timer
10310 * is enabled. Initially, the timer is disabled. As soon as the first source
10311 * value arrives, it is forwarded to the output Observable, and then the timer
10312 * is enabled. After `duration` milliseconds (or the time unit determined
10313 * internally by the optional `scheduler`) has passed, the timer is disabled,
10314 * and this process repeats for the next source value. Optionally takes a
10315 * {@link IScheduler} for managing timers.
10317 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
10318 * var clicks = Rx.Observable.fromEvent(document, 'click');
10319 * var result = clicks.throttleTime(1000);
10320 * result.subscribe(x => console.log(x));
10322 * @see {@link auditTime}
10323 * @see {@link debounceTime}
10324 * @see {@link delay}
10325 * @see {@link sampleTime}
10326 * @see {@link throttle}
10328 * @param {number} duration Time to wait before emitting another value after
10329 * emitting the last value, measured in milliseconds or the time unit determined
10330 * internally by the optional `scheduler`.
10331 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
10332 * managing the timers that handle the throttling.
10333 * @return {Observable<T>} An Observable that performs the throttle operation to
10334 * limit the rate of emissions from the source.
10335 * @method throttleTime
10336 * @owner Observable
10338 function throttleTime(duration, scheduler, config) {
10339 if (scheduler === void 0) { scheduler = async_1.async; }
10340 if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
10341 return throttleTime_1.throttleTime(duration, scheduler, config)(this);
10343 exports.throttleTime = throttleTime;
10345 },{"../operators/throttle":193,"../operators/throttleTime":194,"../scheduler/async":203}],150:[function(require,module,exports){
10347 var async_1 = require('../scheduler/async');
10348 var timeout_1 = require('../operators/timeout');
10351 * Errors if Observable does not emit a value in given time span.
10353 * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
10355 * <img src="./img/timeout.png" width="100%">
10357 * `timeout` operator accepts as an argument either a number or a Date.
10359 * If number was provided, it returns an Observable that behaves like a source
10360 * Observable, unless there is a period of time where there is no value emitted.
10361 * So if you provide `100` as argument and first value comes after 50ms from
10362 * the moment of subscription, this value will be simply re-emitted by the resulting
10363 * Observable. If however after that 100ms passes without a second value being emitted,
10364 * stream will end with an error and source Observable will be unsubscribed.
10365 * These checks are performed throughout whole lifecycle of Observable - from the moment
10366 * it was subscribed to, until it completes or errors itself. Thus every value must be
10367 * emitted within specified period since previous value.
10369 * If provided argument was Date, returned Observable behaves differently. It throws
10370 * if Observable did not complete before provided Date. This means that periods between
10371 * emission of particular values do not matter in this case. If Observable did not complete
10372 * before provided Date, source Observable will be unsubscribed. Other than that, resulting
10373 * stream behaves just as source Observable.
10375 * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
10376 * when returned Observable will check if source stream emitted value or completed.
10378 * @example <caption>Check if ticks are emitted within certain timespan</caption>
10379 * const seconds = Rx.Observable.interval(1000);
10381 * seconds.timeout(1100) // Let's use bigger timespan to be safe,
10382 * // since `interval` might fire a bit later then scheduled.
10384 * value => console.log(value), // Will emit numbers just as regular `interval` would.
10385 * err => console.log(err) // Will never be called.
10388 * seconds.timeout(900).subscribe(
10389 * value => console.log(value), // Will never be called.
10390 * err => console.log(err) // Will emit error before even first value is emitted,
10391 * // since it did not arrive within 900ms period.
10394 * @example <caption>Use Date to check if Observable completed</caption>
10395 * const seconds = Rx.Observable.interval(1000);
10397 * seconds.timeout(new Date("December 17, 2020 03:24:00"))
10399 * value => console.log(value), // Will emit values as regular `interval` would
10400 * // until December 17, 2020 at 03:24:00.
10401 * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
10402 * // since Observable did not complete by then.
10405 * @see {@link timeoutWith}
10407 * @param {number|Date} due Number specifying period within which Observable must emit values
10408 * or Date specifying before when Observable should complete
10409 * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
10410 * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
10412 * @owner Observable
10414 function timeout(due, scheduler) {
10415 if (scheduler === void 0) { scheduler = async_1.async; }
10416 return timeout_1.timeout(due, scheduler)(this);
10418 exports.timeout = timeout;
10420 },{"../operators/timeout":195,"../scheduler/async":203}],151:[function(require,module,exports){
10422 var withLatestFrom_1 = require('../operators/withLatestFrom');
10423 /* tslint:enable:max-line-length */
10425 * Combines the source Observable with other Observables to create an Observable
10426 * whose values are calculated from the latest values of each, only when the
10429 * <span class="informal">Whenever the source Observable emits a value, it
10430 * computes a formula using that value plus the latest values from other input
10431 * Observables, then emits the output of that formula.</span>
10433 * <img src="./img/withLatestFrom.png" width="100%">
10435 * `withLatestFrom` combines each value from the source Observable (the
10436 * instance) with the latest values from the other input Observables only when
10437 * the source emits a value, optionally using a `project` function to determine
10438 * the value to be emitted on the output Observable. All input Observables must
10439 * emit at least one value before the output Observable will emit a value.
10441 * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
10442 * var clicks = Rx.Observable.fromEvent(document, 'click');
10443 * var timer = Rx.Observable.interval(1000);
10444 * var result = clicks.withLatestFrom(timer);
10445 * result.subscribe(x => console.log(x));
10447 * @see {@link combineLatest}
10449 * @param {ObservableInput} other An input Observable to combine with the source
10450 * Observable. More than one input Observables may be given as argument.
10451 * @param {Function} [project] Projection function for combining values
10452 * together. Receives all values in order of the Observables passed, where the
10453 * first parameter is a value from the source Observable. (e.g.
10454 * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
10455 * passed, arrays will be emitted on the output Observable.
10456 * @return {Observable} An Observable of projected values from the most recent
10457 * values from each input Observable, or an array of the most recent values from
10458 * each input Observable.
10459 * @method withLatestFrom
10460 * @owner Observable
10462 function withLatestFrom() {
10464 for (var _i = 0; _i < arguments.length; _i++) {
10465 args[_i - 0] = arguments[_i];
10467 return withLatestFrom_1.withLatestFrom.apply(void 0, args)(this);
10469 exports.withLatestFrom = withLatestFrom;
10471 },{"../operators/withLatestFrom":196}],152:[function(require,module,exports){
10473 var zip_1 = require('../operators/zip');
10474 /* tslint:enable:max-line-length */
10476 * @param observables
10477 * @return {Observable<R>}
10479 * @owner Observable
10481 function zipProto() {
10482 var observables = [];
10483 for (var _i = 0; _i < arguments.length; _i++) {
10484 observables[_i - 0] = arguments[_i];
10486 return zip_1.zip.apply(void 0, observables)(this);
10488 exports.zipProto = zipProto;
10490 },{"../operators/zip":197}],153:[function(require,module,exports){
10492 var __extends = (this && this.__extends) || function (d, b) {
10493 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10494 function __() { this.constructor = d; }
10495 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10497 var OuterSubscriber_1 = require('../OuterSubscriber');
10498 var subscribeToResult_1 = require('../util/subscribeToResult');
10500 * Buffers the source Observable values until `closingNotifier` emits.
10502 * <span class="informal">Collects values from the past as an array, and emits
10503 * that array only when another Observable emits.</span>
10505 * <img src="./img/buffer.png" width="100%">
10507 * Buffers the incoming Observable values until the given `closingNotifier`
10508 * Observable emits a value, at which point it emits the buffer on the output
10509 * Observable and starts a new buffer internally, awaiting the next time
10510 * `closingNotifier` emits.
10512 * @example <caption>On every click, emit array of most recent interval events</caption>
10513 * var clicks = Rx.Observable.fromEvent(document, 'click');
10514 * var interval = Rx.Observable.interval(1000);
10515 * var buffered = interval.buffer(clicks);
10516 * buffered.subscribe(x => console.log(x));
10518 * @see {@link bufferCount}
10519 * @see {@link bufferTime}
10520 * @see {@link bufferToggle}
10521 * @see {@link bufferWhen}
10522 * @see {@link window}
10524 * @param {Observable<any>} closingNotifier An Observable that signals the
10525 * buffer to be emitted on the output Observable.
10526 * @return {Observable<T[]>} An Observable of buffers, which are arrays of
10529 * @owner Observable
10531 function buffer(closingNotifier) {
10532 return function bufferOperatorFunction(source) {
10533 return source.lift(new BufferOperator(closingNotifier));
10536 exports.buffer = buffer;
10537 var BufferOperator = (function () {
10538 function BufferOperator(closingNotifier) {
10539 this.closingNotifier = closingNotifier;
10541 BufferOperator.prototype.call = function (subscriber, source) {
10542 return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
10544 return BufferOperator;
10547 * We need this JSDoc comment for affecting ESDoc.
10549 * @extends {Ignored}
10551 var BufferSubscriber = (function (_super) {
10552 __extends(BufferSubscriber, _super);
10553 function BufferSubscriber(destination, closingNotifier) {
10554 _super.call(this, destination);
10556 this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
10558 BufferSubscriber.prototype._next = function (value) {
10559 this.buffer.push(value);
10561 BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10562 var buffer = this.buffer;
10564 this.destination.next(buffer);
10566 return BufferSubscriber;
10567 }(OuterSubscriber_1.OuterSubscriber));
10569 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],154:[function(require,module,exports){
10571 var __extends = (this && this.__extends) || function (d, b) {
10572 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10573 function __() { this.constructor = d; }
10574 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10576 var Subscriber_1 = require('../Subscriber');
10578 * Buffers the source Observable values until the size hits the maximum
10579 * `bufferSize` given.
10581 * <span class="informal">Collects values from the past as an array, and emits
10582 * that array only when its size reaches `bufferSize`.</span>
10584 * <img src="./img/bufferCount.png" width="100%">
10586 * Buffers a number of values from the source Observable by `bufferSize` then
10587 * emits the buffer and clears it, and starts a new buffer each
10588 * `startBufferEvery` values. If `startBufferEvery` is not provided or is
10589 * `null`, then new buffers are started immediately at the start of the source
10590 * and when each buffer closes and is emitted.
10592 * @example <caption>Emit the last two click events as an array</caption>
10593 * var clicks = Rx.Observable.fromEvent(document, 'click');
10594 * var buffered = clicks.bufferCount(2);
10595 * buffered.subscribe(x => console.log(x));
10597 * @example <caption>On every click, emit the last two click events as an array</caption>
10598 * var clicks = Rx.Observable.fromEvent(document, 'click');
10599 * var buffered = clicks.bufferCount(2, 1);
10600 * buffered.subscribe(x => console.log(x));
10602 * @see {@link buffer}
10603 * @see {@link bufferTime}
10604 * @see {@link bufferToggle}
10605 * @see {@link bufferWhen}
10606 * @see {@link pairwise}
10607 * @see {@link windowCount}
10609 * @param {number} bufferSize The maximum size of the buffer emitted.
10610 * @param {number} [startBufferEvery] Interval at which to start a new buffer.
10611 * For example if `startBufferEvery` is `2`, then a new buffer will be started
10612 * on every other value from the source. A new buffer is started at the
10613 * beginning of the source by default.
10614 * @return {Observable<T[]>} An Observable of arrays of buffered values.
10615 * @method bufferCount
10616 * @owner Observable
10618 function bufferCount(bufferSize, startBufferEvery) {
10619 if (startBufferEvery === void 0) { startBufferEvery = null; }
10620 return function bufferCountOperatorFunction(source) {
10621 return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
10624 exports.bufferCount = bufferCount;
10625 var BufferCountOperator = (function () {
10626 function BufferCountOperator(bufferSize, startBufferEvery) {
10627 this.bufferSize = bufferSize;
10628 this.startBufferEvery = startBufferEvery;
10629 if (!startBufferEvery || bufferSize === startBufferEvery) {
10630 this.subscriberClass = BufferCountSubscriber;
10633 this.subscriberClass = BufferSkipCountSubscriber;
10636 BufferCountOperator.prototype.call = function (subscriber, source) {
10637 return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
10639 return BufferCountOperator;
10642 * We need this JSDoc comment for affecting ESDoc.
10644 * @extends {Ignored}
10646 var BufferCountSubscriber = (function (_super) {
10647 __extends(BufferCountSubscriber, _super);
10648 function BufferCountSubscriber(destination, bufferSize) {
10649 _super.call(this, destination);
10650 this.bufferSize = bufferSize;
10653 BufferCountSubscriber.prototype._next = function (value) {
10654 var buffer = this.buffer;
10655 buffer.push(value);
10656 if (buffer.length == this.bufferSize) {
10657 this.destination.next(buffer);
10661 BufferCountSubscriber.prototype._complete = function () {
10662 var buffer = this.buffer;
10663 if (buffer.length > 0) {
10664 this.destination.next(buffer);
10666 _super.prototype._complete.call(this);
10668 return BufferCountSubscriber;
10669 }(Subscriber_1.Subscriber));
10671 * We need this JSDoc comment for affecting ESDoc.
10673 * @extends {Ignored}
10675 var BufferSkipCountSubscriber = (function (_super) {
10676 __extends(BufferSkipCountSubscriber, _super);
10677 function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
10678 _super.call(this, destination);
10679 this.bufferSize = bufferSize;
10680 this.startBufferEvery = startBufferEvery;
10684 BufferSkipCountSubscriber.prototype._next = function (value) {
10685 var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
10687 if (count % startBufferEvery === 0) {
10690 for (var i = buffers.length; i--;) {
10691 var buffer = buffers[i];
10692 buffer.push(value);
10693 if (buffer.length === bufferSize) {
10694 buffers.splice(i, 1);
10695 this.destination.next(buffer);
10699 BufferSkipCountSubscriber.prototype._complete = function () {
10700 var _a = this, buffers = _a.buffers, destination = _a.destination;
10701 while (buffers.length > 0) {
10702 var buffer = buffers.shift();
10703 if (buffer.length > 0) {
10704 destination.next(buffer);
10707 _super.prototype._complete.call(this);
10709 return BufferSkipCountSubscriber;
10710 }(Subscriber_1.Subscriber));
10712 },{"../Subscriber":36}],155:[function(require,module,exports){
10714 var __extends = (this && this.__extends) || function (d, b) {
10715 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10716 function __() { this.constructor = d; }
10717 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10719 var Subscription_1 = require('../Subscription');
10720 var tryCatch_1 = require('../util/tryCatch');
10721 var errorObject_1 = require('../util/errorObject');
10722 var OuterSubscriber_1 = require('../OuterSubscriber');
10723 var subscribeToResult_1 = require('../util/subscribeToResult');
10725 * Buffers the source Observable values, using a factory function of closing
10726 * Observables to determine when to close, emit, and reset the buffer.
10728 * <span class="informal">Collects values from the past as an array. When it
10729 * starts collecting values, it calls a function that returns an Observable that
10730 * tells when to close the buffer and restart collecting.</span>
10732 * <img src="./img/bufferWhen.png" width="100%">
10734 * Opens a buffer immediately, then closes the buffer when the observable
10735 * returned by calling `closingSelector` function emits a value. When it closes
10736 * the buffer, it immediately opens a new buffer and repeats the process.
10738 * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
10739 * var clicks = Rx.Observable.fromEvent(document, 'click');
10740 * var buffered = clicks.bufferWhen(() =>
10741 * Rx.Observable.interval(1000 + Math.random() * 4000)
10743 * buffered.subscribe(x => console.log(x));
10745 * @see {@link buffer}
10746 * @see {@link bufferCount}
10747 * @see {@link bufferTime}
10748 * @see {@link bufferToggle}
10749 * @see {@link windowWhen}
10751 * @param {function(): Observable} closingSelector A function that takes no
10752 * arguments and returns an Observable that signals buffer closure.
10753 * @return {Observable<T[]>} An observable of arrays of buffered values.
10754 * @method bufferWhen
10755 * @owner Observable
10757 function bufferWhen(closingSelector) {
10758 return function (source) {
10759 return source.lift(new BufferWhenOperator(closingSelector));
10762 exports.bufferWhen = bufferWhen;
10763 var BufferWhenOperator = (function () {
10764 function BufferWhenOperator(closingSelector) {
10765 this.closingSelector = closingSelector;
10767 BufferWhenOperator.prototype.call = function (subscriber, source) {
10768 return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
10770 return BufferWhenOperator;
10773 * We need this JSDoc comment for affecting ESDoc.
10775 * @extends {Ignored}
10777 var BufferWhenSubscriber = (function (_super) {
10778 __extends(BufferWhenSubscriber, _super);
10779 function BufferWhenSubscriber(destination, closingSelector) {
10780 _super.call(this, destination);
10781 this.closingSelector = closingSelector;
10782 this.subscribing = false;
10785 BufferWhenSubscriber.prototype._next = function (value) {
10786 this.buffer.push(value);
10788 BufferWhenSubscriber.prototype._complete = function () {
10789 var buffer = this.buffer;
10791 this.destination.next(buffer);
10793 _super.prototype._complete.call(this);
10795 BufferWhenSubscriber.prototype._unsubscribe = function () {
10796 this.buffer = null;
10797 this.subscribing = false;
10799 BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10802 BufferWhenSubscriber.prototype.notifyComplete = function () {
10803 if (this.subscribing) {
10810 BufferWhenSubscriber.prototype.openBuffer = function () {
10811 var closingSubscription = this.closingSubscription;
10812 if (closingSubscription) {
10813 this.remove(closingSubscription);
10814 closingSubscription.unsubscribe();
10816 var buffer = this.buffer;
10818 this.destination.next(buffer);
10821 var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
10822 if (closingNotifier === errorObject_1.errorObject) {
10823 this.error(errorObject_1.errorObject.e);
10826 closingSubscription = new Subscription_1.Subscription();
10827 this.closingSubscription = closingSubscription;
10828 this.add(closingSubscription);
10829 this.subscribing = true;
10830 closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
10831 this.subscribing = false;
10834 return BufferWhenSubscriber;
10835 }(OuterSubscriber_1.OuterSubscriber));
10837 },{"../OuterSubscriber":31,"../Subscription":37,"../util/errorObject":215,"../util/subscribeToResult":228,"../util/tryCatch":230}],156:[function(require,module,exports){
10839 var __extends = (this && this.__extends) || function (d, b) {
10840 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10841 function __() { this.constructor = d; }
10842 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10844 var OuterSubscriber_1 = require('../OuterSubscriber');
10845 var subscribeToResult_1 = require('../util/subscribeToResult');
10847 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
10849 * <img src="./img/catch.png" width="100%">
10851 * @example <caption>Continues with a different Observable when there's an error</caption>
10853 * Observable.of(1, 2, 3, 4, 5)
10860 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
10861 * .subscribe(x => console.log(x));
10862 * // 1, 2, 3, I, II, III, IV, V
10864 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
10866 * Observable.of(1, 2, 3, 4, 5)
10873 * .catch((err, caught) => caught)
10875 * .subscribe(x => console.log(x));
10876 * // 1, 2, 3, 1, 2, 3, ...
10878 * @example <caption>Throws a new error when the source Observable throws an error</caption>
10880 * Observable.of(1, 2, 3, 4, 5)
10888 * throw 'error in source. Details: ' + err;
10891 * x => console.log(x),
10892 * err => console.log(err)
10894 * // 1, 2, 3, error in source. Details: four!
10896 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
10897 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
10898 * is returned by the `selector` will be used to continue the observable chain.
10899 * @return {Observable} An observable that originates from either the source or the observable returned by the
10900 * catch `selector` function.
10903 function catchError(selector) {
10904 return function catchErrorOperatorFunction(source) {
10905 var operator = new CatchOperator(selector);
10906 var caught = source.lift(operator);
10907 return (operator.caught = caught);
10910 exports.catchError = catchError;
10911 var CatchOperator = (function () {
10912 function CatchOperator(selector) {
10913 this.selector = selector;
10915 CatchOperator.prototype.call = function (subscriber, source) {
10916 return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
10918 return CatchOperator;
10921 * We need this JSDoc comment for affecting ESDoc.
10923 * @extends {Ignored}
10925 var CatchSubscriber = (function (_super) {
10926 __extends(CatchSubscriber, _super);
10927 function CatchSubscriber(destination, selector, caught) {
10928 _super.call(this, destination);
10929 this.selector = selector;
10930 this.caught = caught;
10932 // NOTE: overriding `error` instead of `_error` because we don't want
10933 // to have this flag this subscriber as `isStopped`. We can mimic the
10934 // behavior of the RetrySubscriber (from the `retry` operator), where
10935 // we unsubscribe from our source chain, reset our Subscriber flags,
10936 // then subscribe to the selector result.
10937 CatchSubscriber.prototype.error = function (err) {
10938 if (!this.isStopped) {
10939 var result = void 0;
10941 result = this.selector(err, this.caught);
10944 _super.prototype.error.call(this, err2);
10947 this._unsubscribeAndRecycle();
10948 this.add(subscribeToResult_1.subscribeToResult(this, result));
10951 return CatchSubscriber;
10952 }(OuterSubscriber_1.OuterSubscriber));
10954 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],157:[function(require,module,exports){
10956 var __extends = (this && this.__extends) || function (d, b) {
10957 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10958 function __() { this.constructor = d; }
10959 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10961 var ArrayObservable_1 = require('../observable/ArrayObservable');
10962 var isArray_1 = require('../util/isArray');
10963 var OuterSubscriber_1 = require('../OuterSubscriber');
10964 var subscribeToResult_1 = require('../util/subscribeToResult');
10966 /* tslint:enable:max-line-length */
10968 * Combines multiple Observables to create an Observable whose values are
10969 * calculated from the latest values of each of its input Observables.
10971 * <span class="informal">Whenever any input Observable emits a value, it
10972 * computes a formula using the latest values from all the inputs, then emits
10973 * the output of that formula.</span>
10975 * <img src="./img/combineLatest.png" width="100%">
10977 * `combineLatest` combines the values from this Observable with values from
10978 * Observables passed as arguments. This is done by subscribing to each
10979 * Observable, in order, and collecting an array of each of the most recent
10980 * values any time any of the input Observables emits, then either taking that
10981 * array and passing it as arguments to an optional `project` function and
10982 * emitting the return value of that, or just emitting the array of recent
10983 * values directly if there is no `project` function.
10985 * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
10986 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
10987 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
10988 * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
10989 * bmi.subscribe(x => console.log('BMI is ' + x));
10991 * // With output to console:
10992 * // BMI is 24.212293388429753
10993 * // BMI is 23.93948099205209
10994 * // BMI is 23.671253629592222
10996 * @see {@link combineAll}
10997 * @see {@link merge}
10998 * @see {@link withLatestFrom}
11000 * @param {ObservableInput} other An input Observable to combine with the source
11001 * Observable. More than one input Observables may be given as argument.
11002 * @param {function} [project] An optional function to project the values from
11003 * the combined latest values into a new value on the output Observable.
11004 * @return {Observable} An Observable of projected values from the most recent
11005 * values from each input Observable, or an array of the most recent values from
11006 * each input Observable.
11007 * @method combineLatest
11008 * @owner Observable
11010 function combineLatest() {
11011 var observables = [];
11012 for (var _i = 0; _i < arguments.length; _i++) {
11013 observables[_i - 0] = arguments[_i];
11015 var project = null;
11016 if (typeof observables[observables.length - 1] === 'function') {
11017 project = observables.pop();
11019 // if the first and only other argument besides the resultSelector is an array
11020 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
11021 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
11022 observables = observables[0].slice();
11024 return function (source) { return source.lift.call(new ArrayObservable_1.ArrayObservable([source].concat(observables)), new CombineLatestOperator(project)); };
11026 exports.combineLatest = combineLatest;
11027 var CombineLatestOperator = (function () {
11028 function CombineLatestOperator(project) {
11029 this.project = project;
11031 CombineLatestOperator.prototype.call = function (subscriber, source) {
11032 return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
11034 return CombineLatestOperator;
11036 exports.CombineLatestOperator = CombineLatestOperator;
11038 * We need this JSDoc comment for affecting ESDoc.
11040 * @extends {Ignored}
11042 var CombineLatestSubscriber = (function (_super) {
11043 __extends(CombineLatestSubscriber, _super);
11044 function CombineLatestSubscriber(destination, project) {
11045 _super.call(this, destination);
11046 this.project = project;
11049 this.observables = [];
11051 CombineLatestSubscriber.prototype._next = function (observable) {
11052 this.values.push(none);
11053 this.observables.push(observable);
11055 CombineLatestSubscriber.prototype._complete = function () {
11056 var observables = this.observables;
11057 var len = observables.length;
11059 this.destination.complete();
11063 this.toRespond = len;
11064 for (var i = 0; i < len; i++) {
11065 var observable = observables[i];
11066 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
11070 CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
11071 if ((this.active -= 1) === 0) {
11072 this.destination.complete();
11075 CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11076 var values = this.values;
11077 var oldVal = values[outerIndex];
11078 var toRespond = !this.toRespond
11080 : oldVal === none ? --this.toRespond : this.toRespond;
11081 values[outerIndex] = innerValue;
11082 if (toRespond === 0) {
11083 if (this.project) {
11084 this._tryProject(values);
11087 this.destination.next(values.slice());
11091 CombineLatestSubscriber.prototype._tryProject = function (values) {
11094 result = this.project.apply(this, values);
11097 this.destination.error(err);
11100 this.destination.next(result);
11102 return CombineLatestSubscriber;
11103 }(OuterSubscriber_1.OuterSubscriber));
11104 exports.CombineLatestSubscriber = CombineLatestSubscriber;
11106 },{"../OuterSubscriber":31,"../observable/ArrayObservable":90,"../util/isArray":217,"../util/subscribeToResult":228}],158:[function(require,module,exports){
11108 var concat_1 = require('../observable/concat');
11109 /* tslint:enable:max-line-length */
11111 * Creates an output Observable which sequentially emits all values from every
11112 * given input Observable after the current Observable.
11114 * <span class="informal">Concatenates multiple Observables together by
11115 * sequentially emitting their values, one Observable after the other.</span>
11117 * <img src="./img/concat.png" width="100%">
11119 * Joins this Observable with multiple other Observables by subscribing to them
11120 * one at a time, starting with the source, and merging their results into the
11121 * output Observable. Will wait for each Observable to complete before moving
11124 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
11125 * var timer = Rx.Observable.interval(1000).take(4);
11126 * var sequence = Rx.Observable.range(1, 10);
11127 * var result = timer.concat(sequence);
11128 * result.subscribe(x => console.log(x));
11131 * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
11133 * @example <caption>Concatenate 3 Observables</caption>
11134 * var timer1 = Rx.Observable.interval(1000).take(10);
11135 * var timer2 = Rx.Observable.interval(2000).take(6);
11136 * var timer3 = Rx.Observable.interval(500).take(10);
11137 * var result = timer1.concat(timer2, timer3);
11138 * result.subscribe(x => console.log(x));
11140 * // results in the following:
11141 * // (Prints to console sequentially)
11142 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
11143 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
11144 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
11146 * @see {@link concatAll}
11147 * @see {@link concatMap}
11148 * @see {@link concatMapTo}
11150 * @param {ObservableInput} other An input Observable to concatenate after the source
11151 * Observable. More than one input Observables may be given as argument.
11152 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
11153 * Observable subscription on.
11154 * @return {Observable} All values of each passed Observable merged into a
11155 * single Observable, in order, in serial fashion.
11157 * @owner Observable
11159 function concat() {
11160 var observables = [];
11161 for (var _i = 0; _i < arguments.length; _i++) {
11162 observables[_i - 0] = arguments[_i];
11164 return function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); };
11166 exports.concat = concat;
11168 },{"../observable/concat":102}],159:[function(require,module,exports){
11170 var mergeAll_1 = require('./mergeAll');
11172 * Converts a higher-order Observable into a first-order Observable by
11173 * concatenating the inner Observables in order.
11175 * <span class="informal">Flattens an Observable-of-Observables by putting one
11176 * inner Observable after the other.</span>
11178 * <img src="./img/concatAll.png" width="100%">
11180 * Joins every Observable emitted by the source (a higher-order Observable), in
11181 * a serial fashion. It subscribes to each inner Observable only after the
11182 * previous inner Observable has completed, and merges all of their values into
11183 * the returned observable.
11185 * __Warning:__ If the source Observable emits Observables quickly and
11186 * endlessly, and the inner Observables it emits generally complete slower than
11187 * the source emits, you can run into memory issues as the incoming Observables
11188 * collect in an unbounded buffer.
11190 * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
11193 * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
11194 * var clicks = Rx.Observable.fromEvent(document, 'click');
11195 * var higherOrder = clicks.map(ev => Rx.Observable.interval(1000).take(4));
11196 * var firstOrder = higherOrder.concatAll();
11197 * firstOrder.subscribe(x => console.log(x));
11199 * // Results in the following:
11200 * // (results are not concurrent)
11201 * // For every click on the "document" it will emit values 0 to 3 spaced
11202 * // on a 1000ms interval
11203 * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
11205 * @see {@link combineAll}
11206 * @see {@link concat}
11207 * @see {@link concatMap}
11208 * @see {@link concatMapTo}
11209 * @see {@link exhaust}
11210 * @see {@link mergeAll}
11211 * @see {@link switch}
11212 * @see {@link zipAll}
11214 * @return {Observable} An Observable emitting values from all the inner
11215 * Observables concatenated.
11216 * @method concatAll
11217 * @owner Observable
11219 function concatAll() {
11220 return mergeAll_1.mergeAll(1);
11222 exports.concatAll = concatAll;
11224 },{"./mergeAll":171}],160:[function(require,module,exports){
11226 var __extends = (this && this.__extends) || function (d, b) {
11227 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11228 function __() { this.constructor = d; }
11229 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11231 var Subscriber_1 = require('../Subscriber');
11232 var async_1 = require('../scheduler/async');
11234 * Emits a value from the source Observable only after a particular time span
11235 * has passed without another source emission.
11237 * <span class="informal">It's like {@link delay}, but passes only the most
11238 * recent value from each burst of emissions.</span>
11240 * <img src="./img/debounceTime.png" width="100%">
11242 * `debounceTime` delays values emitted by the source Observable, but drops
11243 * previous pending delayed emissions if a new value arrives on the source
11244 * Observable. This operator keeps track of the most recent value from the
11245 * source Observable, and emits that only when `dueTime` enough time has passed
11246 * without any other value appearing on the source Observable. If a new value
11247 * appears before `dueTime` silence occurs, the previous value will be dropped
11248 * and will not be emitted on the output Observable.
11250 * This is a rate-limiting operator, because it is impossible for more than one
11251 * value to be emitted in any time window of duration `dueTime`, but it is also
11252 * a delay-like operator since output emissions do not occur at the same time as
11253 * they did on the source Observable. Optionally takes a {@link IScheduler} for
11256 * @example <caption>Emit the most recent click after a burst of clicks</caption>
11257 * var clicks = Rx.Observable.fromEvent(document, 'click');
11258 * var result = clicks.debounceTime(1000);
11259 * result.subscribe(x => console.log(x));
11261 * @see {@link auditTime}
11262 * @see {@link debounce}
11263 * @see {@link delay}
11264 * @see {@link sampleTime}
11265 * @see {@link throttleTime}
11267 * @param {number} dueTime The timeout duration in milliseconds (or the time
11268 * unit determined internally by the optional `scheduler`) for the window of
11269 * time required to wait for emission silence before emitting the most recent
11271 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
11272 * managing the timers that handle the timeout for each value.
11273 * @return {Observable} An Observable that delays the emissions of the source
11274 * Observable by the specified `dueTime`, and may drop some values if they occur
11276 * @method debounceTime
11277 * @owner Observable
11279 function debounceTime(dueTime, scheduler) {
11280 if (scheduler === void 0) { scheduler = async_1.async; }
11281 return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
11283 exports.debounceTime = debounceTime;
11284 var DebounceTimeOperator = (function () {
11285 function DebounceTimeOperator(dueTime, scheduler) {
11286 this.dueTime = dueTime;
11287 this.scheduler = scheduler;
11289 DebounceTimeOperator.prototype.call = function (subscriber, source) {
11290 return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
11292 return DebounceTimeOperator;
11295 * We need this JSDoc comment for affecting ESDoc.
11297 * @extends {Ignored}
11299 var DebounceTimeSubscriber = (function (_super) {
11300 __extends(DebounceTimeSubscriber, _super);
11301 function DebounceTimeSubscriber(destination, dueTime, scheduler) {
11302 _super.call(this, destination);
11303 this.dueTime = dueTime;
11304 this.scheduler = scheduler;
11305 this.debouncedSubscription = null;
11306 this.lastValue = null;
11307 this.hasValue = false;
11309 DebounceTimeSubscriber.prototype._next = function (value) {
11310 this.clearDebounce();
11311 this.lastValue = value;
11312 this.hasValue = true;
11313 this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
11315 DebounceTimeSubscriber.prototype._complete = function () {
11316 this.debouncedNext();
11317 this.destination.complete();
11319 DebounceTimeSubscriber.prototype.debouncedNext = function () {
11320 this.clearDebounce();
11321 if (this.hasValue) {
11322 this.destination.next(this.lastValue);
11323 this.lastValue = null;
11324 this.hasValue = false;
11327 DebounceTimeSubscriber.prototype.clearDebounce = function () {
11328 var debouncedSubscription = this.debouncedSubscription;
11329 if (debouncedSubscription !== null) {
11330 this.remove(debouncedSubscription);
11331 debouncedSubscription.unsubscribe();
11332 this.debouncedSubscription = null;
11335 return DebounceTimeSubscriber;
11336 }(Subscriber_1.Subscriber));
11337 function dispatchNext(subscriber) {
11338 subscriber.debouncedNext();
11341 },{"../Subscriber":36,"../scheduler/async":203}],161:[function(require,module,exports){
11343 var __extends = (this && this.__extends) || function (d, b) {
11344 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11345 function __() { this.constructor = d; }
11346 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11348 var async_1 = require('../scheduler/async');
11349 var isDate_1 = require('../util/isDate');
11350 var Subscriber_1 = require('../Subscriber');
11351 var Notification_1 = require('../Notification');
11353 * Delays the emission of items from the source Observable by a given timeout or
11354 * until a given Date.
11356 * <span class="informal">Time shifts each item by some specified amount of
11357 * milliseconds.</span>
11359 * <img src="./img/delay.png" width="100%">
11361 * If the delay argument is a Number, this operator time shifts the source
11362 * Observable by that amount of time expressed in milliseconds. The relative
11363 * time intervals between the values are preserved.
11365 * If the delay argument is a Date, this operator time shifts the start of the
11366 * Observable execution until the given date occurs.
11368 * @example <caption>Delay each click by one second</caption>
11369 * var clicks = Rx.Observable.fromEvent(document, 'click');
11370 * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
11371 * delayedClicks.subscribe(x => console.log(x));
11373 * @example <caption>Delay all clicks until a future date happens</caption>
11374 * var clicks = Rx.Observable.fromEvent(document, 'click');
11375 * var date = new Date('March 15, 2050 12:00:00'); // in the future
11376 * var delayedClicks = clicks.delay(date); // click emitted only after that date
11377 * delayedClicks.subscribe(x => console.log(x));
11379 * @see {@link debounceTime}
11380 * @see {@link delayWhen}
11382 * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
11383 * a `Date` until which the emission of the source items is delayed.
11384 * @param {Scheduler} [scheduler=async] The IScheduler to use for
11385 * managing the timers that handle the time-shift for each item.
11386 * @return {Observable} An Observable that delays the emissions of the source
11387 * Observable by the specified timeout or Date.
11389 * @owner Observable
11391 function delay(delay, scheduler) {
11392 if (scheduler === void 0) { scheduler = async_1.async; }
11393 var absoluteDelay = isDate_1.isDate(delay);
11394 var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
11395 return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
11397 exports.delay = delay;
11398 var DelayOperator = (function () {
11399 function DelayOperator(delay, scheduler) {
11400 this.delay = delay;
11401 this.scheduler = scheduler;
11403 DelayOperator.prototype.call = function (subscriber, source) {
11404 return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
11406 return DelayOperator;
11409 * We need this JSDoc comment for affecting ESDoc.
11411 * @extends {Ignored}
11413 var DelaySubscriber = (function (_super) {
11414 __extends(DelaySubscriber, _super);
11415 function DelaySubscriber(destination, delay, scheduler) {
11416 _super.call(this, destination);
11417 this.delay = delay;
11418 this.scheduler = scheduler;
11420 this.active = false;
11421 this.errored = false;
11423 DelaySubscriber.dispatch = function (state) {
11424 var source = state.source;
11425 var queue = source.queue;
11426 var scheduler = state.scheduler;
11427 var destination = state.destination;
11428 while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
11429 queue.shift().notification.observe(destination);
11431 if (queue.length > 0) {
11432 var delay_1 = Math.max(0, queue[0].time - scheduler.now());
11433 this.schedule(state, delay_1);
11436 source.active = false;
11439 DelaySubscriber.prototype._schedule = function (scheduler) {
11440 this.active = true;
11441 this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
11442 source: this, destination: this.destination, scheduler: scheduler
11445 DelaySubscriber.prototype.scheduleNotification = function (notification) {
11446 if (this.errored === true) {
11449 var scheduler = this.scheduler;
11450 var message = new DelayMessage(scheduler.now() + this.delay, notification);
11451 this.queue.push(message);
11452 if (this.active === false) {
11453 this._schedule(scheduler);
11456 DelaySubscriber.prototype._next = function (value) {
11457 this.scheduleNotification(Notification_1.Notification.createNext(value));
11459 DelaySubscriber.prototype._error = function (err) {
11460 this.errored = true;
11462 this.destination.error(err);
11464 DelaySubscriber.prototype._complete = function () {
11465 this.scheduleNotification(Notification_1.Notification.createComplete());
11467 return DelaySubscriber;
11468 }(Subscriber_1.Subscriber));
11469 var DelayMessage = (function () {
11470 function DelayMessage(time, notification) {
11472 this.notification = notification;
11474 return DelayMessage;
11477 },{"../Notification":28,"../Subscriber":36,"../scheduler/async":203,"../util/isDate":219}],162:[function(require,module,exports){
11479 var __extends = (this && this.__extends) || function (d, b) {
11480 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11481 function __() { this.constructor = d; }
11482 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11484 var OuterSubscriber_1 = require('../OuterSubscriber');
11485 var subscribeToResult_1 = require('../util/subscribeToResult');
11486 var Set_1 = require('../util/Set');
11488 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
11490 * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
11491 * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
11492 * source observable directly with an equality check against previous values.
11494 * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
11496 * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
11497 * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
11498 * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
11499 * that the internal `Set` can be "flushed", basically clearing it of values.
11501 * @example <caption>A simple example with numbers</caption>
11502 * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
11504 * .subscribe(x => console.log(x)); // 1, 2, 3, 4
11506 * @example <caption>An example using a keySelector function</caption>
11507 * interface Person {
11512 * Observable.of<Person>(
11513 * { age: 4, name: 'Foo'},
11514 * { age: 7, name: 'Bar'},
11515 * { age: 5, name: 'Foo'})
11516 * .distinct((p: Person) => p.name)
11517 * .subscribe(x => console.log(x));
11520 * // { age: 4, name: 'Foo' }
11521 * // { age: 7, name: 'Bar' }
11523 * @see {@link distinctUntilChanged}
11524 * @see {@link distinctUntilKeyChanged}
11526 * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
11527 * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
11528 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
11530 * @owner Observable
11532 function distinct(keySelector, flushes) {
11533 return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
11535 exports.distinct = distinct;
11536 var DistinctOperator = (function () {
11537 function DistinctOperator(keySelector, flushes) {
11538 this.keySelector = keySelector;
11539 this.flushes = flushes;
11541 DistinctOperator.prototype.call = function (subscriber, source) {
11542 return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
11544 return DistinctOperator;
11547 * We need this JSDoc comment for affecting ESDoc.
11549 * @extends {Ignored}
11551 var DistinctSubscriber = (function (_super) {
11552 __extends(DistinctSubscriber, _super);
11553 function DistinctSubscriber(destination, keySelector, flushes) {
11554 _super.call(this, destination);
11555 this.keySelector = keySelector;
11556 this.values = new Set_1.Set();
11558 this.add(subscribeToResult_1.subscribeToResult(this, flushes));
11561 DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11562 this.values.clear();
11564 DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
11565 this._error(error);
11567 DistinctSubscriber.prototype._next = function (value) {
11568 if (this.keySelector) {
11569 this._useKeySelector(value);
11572 this._finalizeNext(value, value);
11575 DistinctSubscriber.prototype._useKeySelector = function (value) {
11577 var destination = this.destination;
11579 key = this.keySelector(value);
11582 destination.error(err);
11585 this._finalizeNext(key, value);
11587 DistinctSubscriber.prototype._finalizeNext = function (key, value) {
11588 var values = this.values;
11589 if (!values.has(key)) {
11591 this.destination.next(value);
11594 return DistinctSubscriber;
11595 }(OuterSubscriber_1.OuterSubscriber));
11596 exports.DistinctSubscriber = DistinctSubscriber;
11598 },{"../OuterSubscriber":31,"../util/Set":212,"../util/subscribeToResult":228}],163:[function(require,module,exports){
11600 var __extends = (this && this.__extends) || function (d, b) {
11601 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11602 function __() { this.constructor = d; }
11603 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11605 var Subscriber_1 = require('../Subscriber');
11606 var tryCatch_1 = require('../util/tryCatch');
11607 var errorObject_1 = require('../util/errorObject');
11608 /* tslint:enable:max-line-length */
11610 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
11612 * 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.
11614 * If a comparator function is not provided, an equality check is used by default.
11616 * @example <caption>A simple example with numbers</caption>
11617 * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
11618 * .distinctUntilChanged()
11619 * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
11621 * @example <caption>An example using a compare function</caption>
11622 * interface Person {
11627 * Observable.of<Person>(
11628 * { age: 4, name: 'Foo'},
11629 * { age: 7, name: 'Bar'},
11630 * { age: 5, name: 'Foo'})
11631 * { age: 6, name: 'Foo'})
11632 * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
11633 * .subscribe(x => console.log(x));
11636 * // { age: 4, name: 'Foo' }
11637 * // { age: 7, name: 'Bar' }
11638 * // { age: 5, name: 'Foo' }
11640 * @see {@link distinct}
11641 * @see {@link distinctUntilKeyChanged}
11643 * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
11644 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
11645 * @method distinctUntilChanged
11646 * @owner Observable
11648 function distinctUntilChanged(compare, keySelector) {
11649 return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
11651 exports.distinctUntilChanged = distinctUntilChanged;
11652 var DistinctUntilChangedOperator = (function () {
11653 function DistinctUntilChangedOperator(compare, keySelector) {
11654 this.compare = compare;
11655 this.keySelector = keySelector;
11657 DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
11658 return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
11660 return DistinctUntilChangedOperator;
11663 * We need this JSDoc comment for affecting ESDoc.
11665 * @extends {Ignored}
11667 var DistinctUntilChangedSubscriber = (function (_super) {
11668 __extends(DistinctUntilChangedSubscriber, _super);
11669 function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
11670 _super.call(this, destination);
11671 this.keySelector = keySelector;
11672 this.hasKey = false;
11673 if (typeof compare === 'function') {
11674 this.compare = compare;
11677 DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
11680 DistinctUntilChangedSubscriber.prototype._next = function (value) {
11681 var keySelector = this.keySelector;
11684 key = tryCatch_1.tryCatch(this.keySelector)(value);
11685 if (key === errorObject_1.errorObject) {
11686 return this.destination.error(errorObject_1.errorObject.e);
11689 var result = false;
11691 result = tryCatch_1.tryCatch(this.compare)(this.key, key);
11692 if (result === errorObject_1.errorObject) {
11693 return this.destination.error(errorObject_1.errorObject.e);
11697 this.hasKey = true;
11699 if (Boolean(result) === false) {
11701 this.destination.next(value);
11704 return DistinctUntilChangedSubscriber;
11705 }(Subscriber_1.Subscriber));
11707 },{"../Subscriber":36,"../util/errorObject":215,"../util/tryCatch":230}],164:[function(require,module,exports){
11709 var __extends = (this && this.__extends) || function (d, b) {
11710 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11711 function __() { this.constructor = d; }
11712 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11714 var tryCatch_1 = require('../util/tryCatch');
11715 var errorObject_1 = require('../util/errorObject');
11716 var OuterSubscriber_1 = require('../OuterSubscriber');
11717 var subscribeToResult_1 = require('../util/subscribeToResult');
11718 /* tslint:enable:max-line-length */
11720 * Recursively projects each source value to an Observable which is merged in
11721 * the output Observable.
11723 * <span class="informal">It's similar to {@link mergeMap}, but applies the
11724 * projection function to every source value as well as every output value.
11725 * It's recursive.</span>
11727 * <img src="./img/expand.png" width="100%">
11729 * Returns an Observable that emits items based on applying a function that you
11730 * supply to each item emitted by the source Observable, where that function
11731 * returns an Observable, and then merging those resulting Observables and
11732 * emitting the results of this merger. *Expand* will re-emit on the output
11733 * Observable every source value. Then, each output value is given to the
11734 * `project` function which returns an inner Observable to be merged on the
11735 * output Observable. Those output values resulting from the projection are also
11736 * given to the `project` function to produce new output values. This is how
11737 * *expand* behaves recursively.
11739 * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
11740 * var clicks = Rx.Observable.fromEvent(document, 'click');
11741 * var powersOfTwo = clicks
11743 * .expand(x => Rx.Observable.of(2 * x).delay(1000))
11745 * powersOfTwo.subscribe(x => console.log(x));
11747 * @see {@link mergeMap}
11748 * @see {@link mergeScan}
11750 * @param {function(value: T, index: number) => Observable} project A function
11751 * that, when applied to an item emitted by the source or the output Observable,
11752 * returns an Observable.
11753 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
11754 * Observables being subscribed to concurrently.
11755 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
11756 * each projected inner Observable.
11757 * @return {Observable} An Observable that emits the source values and also
11758 * result of applying the projection function to each value emitted on the
11759 * output Observable and and merging the results of the Observables obtained
11760 * from this transformation.
11762 * @owner Observable
11764 function expand(project, concurrent, scheduler) {
11765 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11766 if (scheduler === void 0) { scheduler = undefined; }
11767 concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
11768 return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
11770 exports.expand = expand;
11771 var ExpandOperator = (function () {
11772 function ExpandOperator(project, concurrent, scheduler) {
11773 this.project = project;
11774 this.concurrent = concurrent;
11775 this.scheduler = scheduler;
11777 ExpandOperator.prototype.call = function (subscriber, source) {
11778 return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
11780 return ExpandOperator;
11782 exports.ExpandOperator = ExpandOperator;
11784 * We need this JSDoc comment for affecting ESDoc.
11786 * @extends {Ignored}
11788 var ExpandSubscriber = (function (_super) {
11789 __extends(ExpandSubscriber, _super);
11790 function ExpandSubscriber(destination, project, concurrent, scheduler) {
11791 _super.call(this, destination);
11792 this.project = project;
11793 this.concurrent = concurrent;
11794 this.scheduler = scheduler;
11797 this.hasCompleted = false;
11798 if (concurrent < Number.POSITIVE_INFINITY) {
11802 ExpandSubscriber.dispatch = function (arg) {
11803 var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
11804 subscriber.subscribeToProjection(result, value, index);
11806 ExpandSubscriber.prototype._next = function (value) {
11807 var destination = this.destination;
11808 if (destination.closed) {
11812 var index = this.index++;
11813 if (this.active < this.concurrent) {
11814 destination.next(value);
11815 var result = tryCatch_1.tryCatch(this.project)(value, index);
11816 if (result === errorObject_1.errorObject) {
11817 destination.error(errorObject_1.errorObject.e);
11819 else if (!this.scheduler) {
11820 this.subscribeToProjection(result, value, index);
11823 var state = { subscriber: this, result: result, value: value, index: index };
11824 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
11828 this.buffer.push(value);
11831 ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
11833 this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
11835 ExpandSubscriber.prototype._complete = function () {
11836 this.hasCompleted = true;
11837 if (this.hasCompleted && this.active === 0) {
11838 this.destination.complete();
11841 ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11842 this._next(innerValue);
11844 ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
11845 var buffer = this.buffer;
11846 this.remove(innerSub);
11848 if (buffer && buffer.length > 0) {
11849 this._next(buffer.shift());
11851 if (this.hasCompleted && this.active === 0) {
11852 this.destination.complete();
11855 return ExpandSubscriber;
11856 }(OuterSubscriber_1.OuterSubscriber));
11857 exports.ExpandSubscriber = ExpandSubscriber;
11859 },{"../OuterSubscriber":31,"../util/errorObject":215,"../util/subscribeToResult":228,"../util/tryCatch":230}],165:[function(require,module,exports){
11861 var __extends = (this && this.__extends) || function (d, b) {
11862 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11863 function __() { this.constructor = d; }
11864 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11866 var Subscriber_1 = require('../Subscriber');
11867 /* tslint:enable:max-line-length */
11869 * Filter items emitted by the source Observable by only emitting those that
11870 * satisfy a specified predicate.
11872 * <span class="informal">Like
11873 * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
11874 * it only emits a value from the source if it passes a criterion function.</span>
11876 * <img src="./img/filter.png" width="100%">
11878 * Similar to the well-known `Array.prototype.filter` method, this operator
11879 * takes values from the source Observable, passes them through a `predicate`
11880 * function and only emits those values that yielded `true`.
11882 * @example <caption>Emit only click events whose target was a DIV element</caption>
11883 * var clicks = Rx.Observable.fromEvent(document, 'click');
11884 * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
11885 * clicksOnDivs.subscribe(x => console.log(x));
11887 * @see {@link distinct}
11888 * @see {@link distinctUntilChanged}
11889 * @see {@link distinctUntilKeyChanged}
11890 * @see {@link ignoreElements}
11891 * @see {@link partition}
11892 * @see {@link skip}
11894 * @param {function(value: T, index: number): boolean} predicate A function that
11895 * evaluates each value emitted by the source Observable. If it returns `true`,
11896 * the value is emitted, if `false` the value is not passed to the output
11897 * Observable. The `index` parameter is the number `i` for the i-th source
11898 * emission that has happened since the subscription, starting from the number
11900 * @param {any} [thisArg] An optional argument to determine the value of `this`
11901 * in the `predicate` function.
11902 * @return {Observable} An Observable of values from the source that were
11903 * allowed by the `predicate` function.
11905 * @owner Observable
11907 function filter(predicate, thisArg) {
11908 return function filterOperatorFunction(source) {
11909 return source.lift(new FilterOperator(predicate, thisArg));
11912 exports.filter = filter;
11913 var FilterOperator = (function () {
11914 function FilterOperator(predicate, thisArg) {
11915 this.predicate = predicate;
11916 this.thisArg = thisArg;
11918 FilterOperator.prototype.call = function (subscriber, source) {
11919 return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
11921 return FilterOperator;
11924 * We need this JSDoc comment for affecting ESDoc.
11926 * @extends {Ignored}
11928 var FilterSubscriber = (function (_super) {
11929 __extends(FilterSubscriber, _super);
11930 function FilterSubscriber(destination, predicate, thisArg) {
11931 _super.call(this, destination);
11932 this.predicate = predicate;
11933 this.thisArg = thisArg;
11936 // the try catch block below is left specifically for
11937 // optimization and perf reasons. a tryCatcher is not necessary here.
11938 FilterSubscriber.prototype._next = function (value) {
11941 result = this.predicate.call(this.thisArg, value, this.count++);
11944 this.destination.error(err);
11948 this.destination.next(value);
11951 return FilterSubscriber;
11952 }(Subscriber_1.Subscriber));
11954 },{"../Subscriber":36}],166:[function(require,module,exports){
11956 var __extends = (this && this.__extends) || function (d, b) {
11957 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11958 function __() { this.constructor = d; }
11959 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11961 var Subscriber_1 = require('../Subscriber');
11962 var Subscription_1 = require('../Subscription');
11964 * Returns an Observable that mirrors the source Observable, but will call a specified function when
11965 * the source terminates on complete or error.
11966 * @param {function} callback Function to be called when source terminates.
11967 * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
11969 * @owner Observable
11971 function finalize(callback) {
11972 return function (source) { return source.lift(new FinallyOperator(callback)); };
11974 exports.finalize = finalize;
11975 var FinallyOperator = (function () {
11976 function FinallyOperator(callback) {
11977 this.callback = callback;
11979 FinallyOperator.prototype.call = function (subscriber, source) {
11980 return source.subscribe(new FinallySubscriber(subscriber, this.callback));
11982 return FinallyOperator;
11985 * We need this JSDoc comment for affecting ESDoc.
11987 * @extends {Ignored}
11989 var FinallySubscriber = (function (_super) {
11990 __extends(FinallySubscriber, _super);
11991 function FinallySubscriber(destination, callback) {
11992 _super.call(this, destination);
11993 this.add(new Subscription_1.Subscription(callback));
11995 return FinallySubscriber;
11996 }(Subscriber_1.Subscriber));
11998 },{"../Subscriber":36,"../Subscription":37}],167:[function(require,module,exports){
12000 var __extends = (this && this.__extends) || function (d, b) {
12001 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12002 function __() { this.constructor = d; }
12003 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12005 var Subscriber_1 = require('../Subscriber');
12006 var EmptyError_1 = require('../util/EmptyError');
12008 * Emits only the first value (or the first value that meets some condition)
12009 * emitted by the source Observable.
12011 * <span class="informal">Emits only the first value. Or emits only the first
12012 * value that passes some test.</span>
12014 * <img src="./img/first.png" width="100%">
12016 * If called with no arguments, `first` emits the first value of the source
12017 * Observable, then completes. If called with a `predicate` function, `first`
12018 * emits the first value of the source that matches the specified condition. It
12019 * may also take a `resultSelector` function to produce the output value from
12020 * the input value, and a `defaultValue` to emit in case the source completes
12021 * before it is able to emit a valid value. Throws an error if `defaultValue`
12022 * was not provided and a matching element is not found.
12024 * @example <caption>Emit only the first click that happens on the DOM</caption>
12025 * var clicks = Rx.Observable.fromEvent(document, 'click');
12026 * var result = clicks.first();
12027 * result.subscribe(x => console.log(x));
12029 * @example <caption>Emits the first click that happens on a DIV</caption>
12030 * var clicks = Rx.Observable.fromEvent(document, 'click');
12031 * var result = clicks.first(ev => ev.target.tagName === 'DIV');
12032 * result.subscribe(x => console.log(x));
12034 * @see {@link filter}
12035 * @see {@link find}
12036 * @see {@link take}
12038 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
12039 * callback if the Observable completes before any `next` notification was sent.
12041 * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
12042 * An optional function called with each item to test for condition matching.
12043 * @param {function(value: T, index: number): R} [resultSelector] A function to
12044 * produce the value on the output Observable based on the values
12045 * and the indices of the source Observable. The arguments passed to this
12047 * - `value`: the value that was emitted on the source.
12048 * - `index`: the "index" of the value from the source.
12049 * @param {R} [defaultValue] The default value emitted in case no valid value
12050 * was found on the source.
12051 * @return {Observable<T|R>} An Observable of the first item that matches the
12054 * @owner Observable
12056 function first(predicate, resultSelector, defaultValue) {
12057 return function (source) { return source.lift(new FirstOperator(predicate, resultSelector, defaultValue, source)); };
12059 exports.first = first;
12060 var FirstOperator = (function () {
12061 function FirstOperator(predicate, resultSelector, defaultValue, source) {
12062 this.predicate = predicate;
12063 this.resultSelector = resultSelector;
12064 this.defaultValue = defaultValue;
12065 this.source = source;
12067 FirstOperator.prototype.call = function (observer, source) {
12068 return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
12070 return FirstOperator;
12073 * We need this JSDoc comment for affecting ESDoc.
12075 * @extends {Ignored}
12077 var FirstSubscriber = (function (_super) {
12078 __extends(FirstSubscriber, _super);
12079 function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
12080 _super.call(this, destination);
12081 this.predicate = predicate;
12082 this.resultSelector = resultSelector;
12083 this.defaultValue = defaultValue;
12084 this.source = source;
12086 this.hasCompleted = false;
12087 this._emitted = false;
12089 FirstSubscriber.prototype._next = function (value) {
12090 var index = this.index++;
12091 if (this.predicate) {
12092 this._tryPredicate(value, index);
12095 this._emit(value, index);
12098 FirstSubscriber.prototype._tryPredicate = function (value, index) {
12101 result = this.predicate(value, index, this.source);
12104 this.destination.error(err);
12108 this._emit(value, index);
12111 FirstSubscriber.prototype._emit = function (value, index) {
12112 if (this.resultSelector) {
12113 this._tryResultSelector(value, index);
12116 this._emitFinal(value);
12118 FirstSubscriber.prototype._tryResultSelector = function (value, index) {
12121 result = this.resultSelector(value, index);
12124 this.destination.error(err);
12127 this._emitFinal(result);
12129 FirstSubscriber.prototype._emitFinal = function (value) {
12130 var destination = this.destination;
12131 if (!this._emitted) {
12132 this._emitted = true;
12133 destination.next(value);
12134 destination.complete();
12135 this.hasCompleted = true;
12138 FirstSubscriber.prototype._complete = function () {
12139 var destination = this.destination;
12140 if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
12141 destination.next(this.defaultValue);
12142 destination.complete();
12144 else if (!this.hasCompleted) {
12145 destination.error(new EmptyError_1.EmptyError);
12148 return FirstSubscriber;
12149 }(Subscriber_1.Subscriber));
12151 },{"../Subscriber":36,"../util/EmptyError":210}],168:[function(require,module,exports){
12153 var __extends = (this && this.__extends) || function (d, b) {
12154 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12155 function __() { this.constructor = d; }
12156 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12158 var Subscriber_1 = require('../Subscriber');
12159 var EmptyError_1 = require('../util/EmptyError');
12160 /* tslint:enable:max-line-length */
12162 * Returns an Observable that emits only the last item emitted by the source Observable.
12163 * It optionally takes a predicate function as a parameter, in which case, rather than emitting
12164 * the last item from the source Observable, the resulting Observable will emit the last item
12165 * from the source Observable that satisfies the predicate.
12167 * <img src="./img/last.png" width="100%">
12169 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
12170 * callback if the Observable completes before any `next` notification was sent.
12171 * @param {function} predicate - The condition any source emitted item has to satisfy.
12172 * @return {Observable} An Observable that emits only the last item satisfying the given condition
12173 * from the source, or an NoSuchElementException if no such items are emitted.
12174 * @throws - Throws if no items that match the predicate are emitted by the source Observable.
12176 * @owner Observable
12178 function last(predicate, resultSelector, defaultValue) {
12179 return function (source) { return source.lift(new LastOperator(predicate, resultSelector, defaultValue, source)); };
12181 exports.last = last;
12182 var LastOperator = (function () {
12183 function LastOperator(predicate, resultSelector, defaultValue, source) {
12184 this.predicate = predicate;
12185 this.resultSelector = resultSelector;
12186 this.defaultValue = defaultValue;
12187 this.source = source;
12189 LastOperator.prototype.call = function (observer, source) {
12190 return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
12192 return LastOperator;
12195 * We need this JSDoc comment for affecting ESDoc.
12197 * @extends {Ignored}
12199 var LastSubscriber = (function (_super) {
12200 __extends(LastSubscriber, _super);
12201 function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
12202 _super.call(this, destination);
12203 this.predicate = predicate;
12204 this.resultSelector = resultSelector;
12205 this.defaultValue = defaultValue;
12206 this.source = source;
12207 this.hasValue = false;
12209 if (typeof defaultValue !== 'undefined') {
12210 this.lastValue = defaultValue;
12211 this.hasValue = true;
12214 LastSubscriber.prototype._next = function (value) {
12215 var index = this.index++;
12216 if (this.predicate) {
12217 this._tryPredicate(value, index);
12220 if (this.resultSelector) {
12221 this._tryResultSelector(value, index);
12224 this.lastValue = value;
12225 this.hasValue = true;
12228 LastSubscriber.prototype._tryPredicate = function (value, index) {
12231 result = this.predicate(value, index, this.source);
12234 this.destination.error(err);
12238 if (this.resultSelector) {
12239 this._tryResultSelector(value, index);
12242 this.lastValue = value;
12243 this.hasValue = true;
12246 LastSubscriber.prototype._tryResultSelector = function (value, index) {
12249 result = this.resultSelector(value, index);
12252 this.destination.error(err);
12255 this.lastValue = result;
12256 this.hasValue = true;
12258 LastSubscriber.prototype._complete = function () {
12259 var destination = this.destination;
12260 if (this.hasValue) {
12261 destination.next(this.lastValue);
12262 destination.complete();
12265 destination.error(new EmptyError_1.EmptyError);
12268 return LastSubscriber;
12269 }(Subscriber_1.Subscriber));
12271 },{"../Subscriber":36,"../util/EmptyError":210}],169:[function(require,module,exports){
12273 var __extends = (this && this.__extends) || function (d, b) {
12274 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12275 function __() { this.constructor = d; }
12276 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12278 var Subscriber_1 = require('../Subscriber');
12280 * Applies a given `project` function to each value emitted by the source
12281 * Observable, and emits the resulting values as an Observable.
12283 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
12284 * it passes each source value through a transformation function to get
12285 * corresponding output values.</span>
12287 * <img src="./img/map.png" width="100%">
12289 * Similar to the well known `Array.prototype.map` function, this operator
12290 * applies a projection to each value and emits that projection in the output
12293 * @example <caption>Map every click to the clientX position of that click</caption>
12294 * var clicks = Rx.Observable.fromEvent(document, 'click');
12295 * var positions = clicks.map(ev => ev.clientX);
12296 * positions.subscribe(x => console.log(x));
12298 * @see {@link mapTo}
12299 * @see {@link pluck}
12301 * @param {function(value: T, index: number): R} project The function to apply
12302 * to each `value` emitted by the source Observable. The `index` parameter is
12303 * the number `i` for the i-th emission that has happened since the
12304 * subscription, starting from the number `0`.
12305 * @param {any} [thisArg] An optional argument to define what `this` is in the
12306 * `project` function.
12307 * @return {Observable<R>} An Observable that emits the values from the source
12308 * Observable transformed by the given `project` function.
12310 * @owner Observable
12312 function map(project, thisArg) {
12313 return function mapOperation(source) {
12314 if (typeof project !== 'function') {
12315 throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
12317 return source.lift(new MapOperator(project, thisArg));
12321 var MapOperator = (function () {
12322 function MapOperator(project, thisArg) {
12323 this.project = project;
12324 this.thisArg = thisArg;
12326 MapOperator.prototype.call = function (subscriber, source) {
12327 return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
12329 return MapOperator;
12331 exports.MapOperator = MapOperator;
12333 * We need this JSDoc comment for affecting ESDoc.
12335 * @extends {Ignored}
12337 var MapSubscriber = (function (_super) {
12338 __extends(MapSubscriber, _super);
12339 function MapSubscriber(destination, project, thisArg) {
12340 _super.call(this, destination);
12341 this.project = project;
12343 this.thisArg = thisArg || this;
12345 // NOTE: This looks unoptimized, but it's actually purposefully NOT
12346 // using try/catch optimizations.
12347 MapSubscriber.prototype._next = function (value) {
12350 result = this.project.call(this.thisArg, value, this.count++);
12353 this.destination.error(err);
12356 this.destination.next(result);
12358 return MapSubscriber;
12359 }(Subscriber_1.Subscriber));
12361 },{"../Subscriber":36}],170:[function(require,module,exports){
12363 var Observable_1 = require('../Observable');
12364 var ArrayObservable_1 = require('../observable/ArrayObservable');
12365 var mergeAll_1 = require('./mergeAll');
12366 var isScheduler_1 = require('../util/isScheduler');
12367 /* tslint:enable:max-line-length */
12369 var observables = [];
12370 for (var _i = 0; _i < arguments.length; _i++) {
12371 observables[_i - 0] = arguments[_i];
12373 return function (source) { return source.lift.call(mergeStatic.apply(void 0, [source].concat(observables))); };
12375 exports.merge = merge;
12376 /* tslint:enable:max-line-length */
12378 * Creates an output Observable which concurrently emits all values from every
12379 * given input Observable.
12381 * <span class="informal">Flattens multiple Observables together by blending
12382 * their values into one Observable.</span>
12384 * <img src="./img/merge.png" width="100%">
12386 * `merge` subscribes to each given input Observable (as arguments), and simply
12387 * forwards (without doing any transformation) all the values from all the input
12388 * Observables to the output Observable. The output Observable only completes
12389 * once all input Observables have completed. Any error delivered by an input
12390 * Observable will be immediately emitted on the output Observable.
12392 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
12393 * var clicks = Rx.Observable.fromEvent(document, 'click');
12394 * var timer = Rx.Observable.interval(1000);
12395 * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
12396 * clicksOrTimer.subscribe(x => console.log(x));
12398 * // Results in the following:
12399 * // timer will emit ascending values, one every second(1000ms) to console
12400 * // clicks logs MouseEvents to console everytime the "document" is clicked
12401 * // Since the two streams are merged you see these happening
12402 * // as they occur.
12404 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
12405 * var timer1 = Rx.Observable.interval(1000).take(10);
12406 * var timer2 = Rx.Observable.interval(2000).take(6);
12407 * var timer3 = Rx.Observable.interval(500).take(10);
12408 * var concurrent = 2; // the argument
12409 * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
12410 * merged.subscribe(x => console.log(x));
12412 * // Results in the following:
12413 * // - First timer1 and timer2 will run concurrently
12414 * // - timer1 will emit a value every 1000ms for 10 iterations
12415 * // - timer2 will emit a value every 2000ms for 6 iterations
12416 * // - after timer1 hits it's max iteration, timer2 will
12417 * // continue, and timer3 will start to run concurrently with timer2
12418 * // - when timer2 hits it's max iteration it terminates, and
12419 * // timer3 will continue to emit a value every 500ms until it is complete
12421 * @see {@link mergeAll}
12422 * @see {@link mergeMap}
12423 * @see {@link mergeMapTo}
12424 * @see {@link mergeScan}
12426 * @param {...ObservableInput} observables Input Observables to merge together.
12427 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
12428 * Observables being subscribed to concurrently.
12429 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
12430 * concurrency of input Observables.
12431 * @return {Observable} an Observable that emits items that are the result of
12432 * every input Observable.
12435 * @owner Observable
12437 function mergeStatic() {
12438 var observables = [];
12439 for (var _i = 0; _i < arguments.length; _i++) {
12440 observables[_i - 0] = arguments[_i];
12442 var concurrent = Number.POSITIVE_INFINITY;
12443 var scheduler = null;
12444 var last = observables[observables.length - 1];
12445 if (isScheduler_1.isScheduler(last)) {
12446 scheduler = observables.pop();
12447 if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
12448 concurrent = observables.pop();
12451 else if (typeof last === 'number') {
12452 concurrent = observables.pop();
12454 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
12455 return observables[0];
12457 return mergeAll_1.mergeAll(concurrent)(new ArrayObservable_1.ArrayObservable(observables, scheduler));
12459 exports.mergeStatic = mergeStatic;
12461 },{"../Observable":29,"../observable/ArrayObservable":90,"../util/isScheduler":224,"./mergeAll":171}],171:[function(require,module,exports){
12463 var mergeMap_1 = require('./mergeMap');
12464 var identity_1 = require('../util/identity');
12466 * Converts a higher-order Observable into a first-order Observable which
12467 * concurrently delivers all values that are emitted on the inner Observables.
12469 * <span class="informal">Flattens an Observable-of-Observables.</span>
12471 * <img src="./img/mergeAll.png" width="100%">
12473 * `mergeAll` subscribes to an Observable that emits Observables, also known as
12474 * a higher-order Observable. Each time it observes one of these emitted inner
12475 * Observables, it subscribes to that and delivers all the values from the
12476 * inner Observable on the output Observable. The output Observable only
12477 * completes once all inner Observables have completed. Any error delivered by
12478 * a inner Observable will be immediately emitted on the output Observable.
12480 * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
12481 * var clicks = Rx.Observable.fromEvent(document, 'click');
12482 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
12483 * var firstOrder = higherOrder.mergeAll();
12484 * firstOrder.subscribe(x => console.log(x));
12486 * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
12487 * var clicks = Rx.Observable.fromEvent(document, 'click');
12488 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
12489 * var firstOrder = higherOrder.mergeAll(2);
12490 * firstOrder.subscribe(x => console.log(x));
12492 * @see {@link combineAll}
12493 * @see {@link concatAll}
12494 * @see {@link exhaust}
12495 * @see {@link merge}
12496 * @see {@link mergeMap}
12497 * @see {@link mergeMapTo}
12498 * @see {@link mergeScan}
12499 * @see {@link switch}
12500 * @see {@link zipAll}
12502 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
12503 * Observables being subscribed to concurrently.
12504 * @return {Observable} An Observable that emits values coming from all the
12505 * inner Observables emitted by the source Observable.
12507 * @owner Observable
12509 function mergeAll(concurrent) {
12510 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12511 return mergeMap_1.mergeMap(identity_1.identity, null, concurrent);
12513 exports.mergeAll = mergeAll;
12515 },{"../util/identity":216,"./mergeMap":172}],172:[function(require,module,exports){
12517 var __extends = (this && this.__extends) || function (d, b) {
12518 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12519 function __() { this.constructor = d; }
12520 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12522 var subscribeToResult_1 = require('../util/subscribeToResult');
12523 var OuterSubscriber_1 = require('../OuterSubscriber');
12524 /* tslint:enable:max-line-length */
12526 * Projects each source value to an Observable which is merged in the output
12529 * <span class="informal">Maps each value to an Observable, then flattens all of
12530 * these inner Observables using {@link mergeAll}.</span>
12532 * <img src="./img/mergeMap.png" width="100%">
12534 * Returns an Observable that emits items based on applying a function that you
12535 * supply to each item emitted by the source Observable, where that function
12536 * returns an Observable, and then merging those resulting Observables and
12537 * emitting the results of this merger.
12539 * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
12540 * var letters = Rx.Observable.of('a', 'b', 'c');
12541 * var result = letters.mergeMap(x =>
12542 * Rx.Observable.interval(1000).map(i => x+i)
12544 * result.subscribe(x => console.log(x));
12546 * // Results in the following:
12553 * // continues to list a,b,c with respective ascending integers
12555 * @see {@link concatMap}
12556 * @see {@link exhaustMap}
12557 * @see {@link merge}
12558 * @see {@link mergeAll}
12559 * @see {@link mergeMapTo}
12560 * @see {@link mergeScan}
12561 * @see {@link switchMap}
12563 * @param {function(value: T, ?index: number): ObservableInput} project A function
12564 * that, when applied to an item emitted by the source Observable, returns an
12566 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
12567 * A function to produce the value on the output Observable based on the values
12568 * and the indices of the source (outer) emission and the inner Observable
12569 * emission. The arguments passed to this function are:
12570 * - `outerValue`: the value that came from the source
12571 * - `innerValue`: the value that came from the projected Observable
12572 * - `outerIndex`: the "index" of the value that came from the source
12573 * - `innerIndex`: the "index" of the value from the projected Observable
12574 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
12575 * Observables being subscribed to concurrently.
12576 * @return {Observable} An Observable that emits the result of applying the
12577 * projection function (and the optional `resultSelector`) to each item emitted
12578 * by the source Observable and merging the results of the Observables obtained
12579 * from this transformation.
12581 * @owner Observable
12583 function mergeMap(project, resultSelector, concurrent) {
12584 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12585 return function mergeMapOperatorFunction(source) {
12586 if (typeof resultSelector === 'number') {
12587 concurrent = resultSelector;
12588 resultSelector = null;
12590 return source.lift(new MergeMapOperator(project, resultSelector, concurrent));
12593 exports.mergeMap = mergeMap;
12594 var MergeMapOperator = (function () {
12595 function MergeMapOperator(project, resultSelector, concurrent) {
12596 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12597 this.project = project;
12598 this.resultSelector = resultSelector;
12599 this.concurrent = concurrent;
12601 MergeMapOperator.prototype.call = function (observer, source) {
12602 return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
12604 return MergeMapOperator;
12606 exports.MergeMapOperator = MergeMapOperator;
12608 * We need this JSDoc comment for affecting ESDoc.
12610 * @extends {Ignored}
12612 var MergeMapSubscriber = (function (_super) {
12613 __extends(MergeMapSubscriber, _super);
12614 function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
12615 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12616 _super.call(this, destination);
12617 this.project = project;
12618 this.resultSelector = resultSelector;
12619 this.concurrent = concurrent;
12620 this.hasCompleted = false;
12625 MergeMapSubscriber.prototype._next = function (value) {
12626 if (this.active < this.concurrent) {
12627 this._tryNext(value);
12630 this.buffer.push(value);
12633 MergeMapSubscriber.prototype._tryNext = function (value) {
12635 var index = this.index++;
12637 result = this.project(value, index);
12640 this.destination.error(err);
12644 this._innerSub(result, value, index);
12646 MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
12647 this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
12649 MergeMapSubscriber.prototype._complete = function () {
12650 this.hasCompleted = true;
12651 if (this.active === 0 && this.buffer.length === 0) {
12652 this.destination.complete();
12655 MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12656 if (this.resultSelector) {
12657 this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
12660 this.destination.next(innerValue);
12663 MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
12666 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
12669 this.destination.error(err);
12672 this.destination.next(result);
12674 MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
12675 var buffer = this.buffer;
12676 this.remove(innerSub);
12678 if (buffer.length > 0) {
12679 this._next(buffer.shift());
12681 else if (this.active === 0 && this.hasCompleted) {
12682 this.destination.complete();
12685 return MergeMapSubscriber;
12686 }(OuterSubscriber_1.OuterSubscriber));
12687 exports.MergeMapSubscriber = MergeMapSubscriber;
12689 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],173:[function(require,module,exports){
12691 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
12692 /* tslint:enable:max-line-length */
12694 * Returns an Observable that emits the results of invoking a specified selector on items
12695 * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
12697 * <img src="./img/multicast.png" width="100%">
12699 * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
12700 * which the source sequence's elements will be multicast to the selector function
12701 * or Subject to push source elements into.
12702 * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
12703 * as many times as needed, without causing multiple subscriptions to the source stream.
12704 * Subscribers to the given source will receive all notifications of the source from the
12705 * time of the subscription forward.
12706 * @return {Observable} An Observable that emits the results of invoking the selector
12707 * on the items emitted by a `ConnectableObservable` that shares a single subscription to
12708 * the underlying stream.
12709 * @method multicast
12710 * @owner Observable
12712 function multicast(subjectOrSubjectFactory, selector) {
12713 return function multicastOperatorFunction(source) {
12714 var subjectFactory;
12715 if (typeof subjectOrSubjectFactory === 'function') {
12716 subjectFactory = subjectOrSubjectFactory;
12719 subjectFactory = function subjectFactory() {
12720 return subjectOrSubjectFactory;
12723 if (typeof selector === 'function') {
12724 return source.lift(new MulticastOperator(subjectFactory, selector));
12726 var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor);
12727 connectable.source = source;
12728 connectable.subjectFactory = subjectFactory;
12729 return connectable;
12732 exports.multicast = multicast;
12733 var MulticastOperator = (function () {
12734 function MulticastOperator(subjectFactory, selector) {
12735 this.subjectFactory = subjectFactory;
12736 this.selector = selector;
12738 MulticastOperator.prototype.call = function (subscriber, source) {
12739 var selector = this.selector;
12740 var subject = this.subjectFactory();
12741 var subscription = selector(subject).subscribe(subscriber);
12742 subscription.add(source.subscribe(subject));
12743 return subscription;
12745 return MulticastOperator;
12747 exports.MulticastOperator = MulticastOperator;
12749 },{"../observable/ConnectableObservable":91}],174:[function(require,module,exports){
12751 var __extends = (this && this.__extends) || function (d, b) {
12752 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12753 function __() { this.constructor = d; }
12754 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12756 var Subscriber_1 = require('../Subscriber');
12757 var Notification_1 = require('../Notification');
12760 * Re-emits all notifications from source Observable with specified scheduler.
12762 * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
12764 * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
12765 * notifications emitted by the source Observable. It might be useful, if you do not have control over
12766 * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
12768 * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
12769 * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
12770 * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
12771 * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
12772 * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
12773 * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
12774 * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
12775 * little bit more, to ensure that they are emitted at expected moments.
12777 * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
12778 * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
12779 * will delay all notifications - including error notifications - while `delay` will pass through error
12780 * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
12781 * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
12782 * for notification emissions in general.
12784 * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
12785 * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
12786 * // with async scheduler by default...
12789 * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame
12790 * .subscribe(val => { // scheduler to ensure smooth animation.
12791 * someDiv.style.height = val + 'px';
12794 * @see {@link delay}
12796 * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
12797 * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
12798 * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
12799 * but with provided scheduler.
12801 * @method observeOn
12802 * @owner Observable
12804 function observeOn(scheduler, delay) {
12805 if (delay === void 0) { delay = 0; }
12806 return function observeOnOperatorFunction(source) {
12807 return source.lift(new ObserveOnOperator(scheduler, delay));
12810 exports.observeOn = observeOn;
12811 var ObserveOnOperator = (function () {
12812 function ObserveOnOperator(scheduler, delay) {
12813 if (delay === void 0) { delay = 0; }
12814 this.scheduler = scheduler;
12815 this.delay = delay;
12817 ObserveOnOperator.prototype.call = function (subscriber, source) {
12818 return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
12820 return ObserveOnOperator;
12822 exports.ObserveOnOperator = ObserveOnOperator;
12824 * We need this JSDoc comment for affecting ESDoc.
12826 * @extends {Ignored}
12828 var ObserveOnSubscriber = (function (_super) {
12829 __extends(ObserveOnSubscriber, _super);
12830 function ObserveOnSubscriber(destination, scheduler, delay) {
12831 if (delay === void 0) { delay = 0; }
12832 _super.call(this, destination);
12833 this.scheduler = scheduler;
12834 this.delay = delay;
12836 ObserveOnSubscriber.dispatch = function (arg) {
12837 var notification = arg.notification, destination = arg.destination;
12838 notification.observe(destination);
12839 this.unsubscribe();
12841 ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
12842 this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
12844 ObserveOnSubscriber.prototype._next = function (value) {
12845 this.scheduleMessage(Notification_1.Notification.createNext(value));
12847 ObserveOnSubscriber.prototype._error = function (err) {
12848 this.scheduleMessage(Notification_1.Notification.createError(err));
12850 ObserveOnSubscriber.prototype._complete = function () {
12851 this.scheduleMessage(Notification_1.Notification.createComplete());
12853 return ObserveOnSubscriber;
12854 }(Subscriber_1.Subscriber));
12855 exports.ObserveOnSubscriber = ObserveOnSubscriber;
12856 var ObserveOnMessage = (function () {
12857 function ObserveOnMessage(notification, destination) {
12858 this.notification = notification;
12859 this.destination = destination;
12861 return ObserveOnMessage;
12863 exports.ObserveOnMessage = ObserveOnMessage;
12865 },{"../Notification":28,"../Subscriber":36}],175:[function(require,module,exports){
12867 var __extends = (this && this.__extends) || function (d, b) {
12868 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12869 function __() { this.constructor = d; }
12870 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12872 var Subscriber_1 = require('../Subscriber');
12874 * Groups pairs of consecutive emissions together and emits them as an array of
12877 * <span class="informal">Puts the current value and previous value together as
12878 * an array, and emits that.</span>
12880 * <img src="./img/pairwise.png" width="100%">
12882 * The Nth emission from the source Observable will cause the output Observable
12883 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
12884 * pair. For this reason, `pairwise` emits on the second and subsequent
12885 * emissions from the source Observable, but not on the first emission, because
12886 * there is no previous value in that case.
12888 * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
12889 * var clicks = Rx.Observable.fromEvent(document, 'click');
12890 * var pairs = clicks.pairwise();
12891 * var distance = pairs.map(pair => {
12892 * var x0 = pair[0].clientX;
12893 * var y0 = pair[0].clientY;
12894 * var x1 = pair[1].clientX;
12895 * var y1 = pair[1].clientY;
12896 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
12898 * distance.subscribe(x => console.log(x));
12900 * @see {@link buffer}
12901 * @see {@link bufferCount}
12903 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
12904 * consecutive values from the source Observable.
12906 * @owner Observable
12908 function pairwise() {
12909 return function (source) { return source.lift(new PairwiseOperator()); };
12911 exports.pairwise = pairwise;
12912 var PairwiseOperator = (function () {
12913 function PairwiseOperator() {
12915 PairwiseOperator.prototype.call = function (subscriber, source) {
12916 return source.subscribe(new PairwiseSubscriber(subscriber));
12918 return PairwiseOperator;
12921 * We need this JSDoc comment for affecting ESDoc.
12923 * @extends {Ignored}
12925 var PairwiseSubscriber = (function (_super) {
12926 __extends(PairwiseSubscriber, _super);
12927 function PairwiseSubscriber(destination) {
12928 _super.call(this, destination);
12929 this.hasPrev = false;
12931 PairwiseSubscriber.prototype._next = function (value) {
12932 if (this.hasPrev) {
12933 this.destination.next([this.prev, value]);
12936 this.hasPrev = true;
12940 return PairwiseSubscriber;
12941 }(Subscriber_1.Subscriber));
12943 },{"../Subscriber":36}],176:[function(require,module,exports){
12945 var map_1 = require('./map');
12947 * Maps each source value (an object) to its specified nested property.
12949 * <span class="informal">Like {@link map}, but meant only for picking one of
12950 * the nested properties of every emitted object.</span>
12952 * <img src="./img/pluck.png" width="100%">
12954 * Given a list of strings describing a path to an object property, retrieves
12955 * the value of a specified nested property from all values in the source
12956 * Observable. If a property can't be resolved, it will return `undefined` for
12959 * @example <caption>Map every click to the tagName of the clicked target element</caption>
12960 * var clicks = Rx.Observable.fromEvent(document, 'click');
12961 * var tagNames = clicks.pluck('target', 'tagName');
12962 * tagNames.subscribe(x => console.log(x));
12966 * @param {...string} properties The nested properties to pluck from each source
12967 * value (an object).
12968 * @return {Observable} A new Observable of property values from the source values.
12970 * @owner Observable
12973 var properties = [];
12974 for (var _i = 0; _i < arguments.length; _i++) {
12975 properties[_i - 0] = arguments[_i];
12977 var length = properties.length;
12978 if (length === 0) {
12979 throw new Error('list of properties cannot be empty.');
12981 return function (source) { return map_1.map(plucker(properties, length))(source); };
12983 exports.pluck = pluck;
12984 function plucker(props, length) {
12985 var mapper = function (x) {
12986 var currentProp = x;
12987 for (var i = 0; i < length; i++) {
12988 var p = currentProp[props[i]];
12989 if (typeof p !== 'undefined') {
12996 return currentProp;
13001 },{"./map":169}],177:[function(require,module,exports){
13003 var Subject_1 = require('../Subject');
13004 var multicast_1 = require('./multicast');
13005 /* tslint:enable:max-line-length */
13007 * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
13008 * before it begins emitting items to those Observers that have subscribed to it.
13010 * <img src="./img/publish.png" width="100%">
13012 * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
13013 * as needed, without causing multiple subscriptions to the source sequence.
13014 * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
13015 * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
13017 * @owner Observable
13019 function publish(selector) {
13021 multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) :
13022 multicast_1.multicast(new Subject_1.Subject());
13024 exports.publish = publish;
13026 },{"../Subject":34,"./multicast":173}],178:[function(require,module,exports){
13028 var ReplaySubject_1 = require('../ReplaySubject');
13029 var multicast_1 = require('./multicast');
13030 /* tslint:enable:max-line-length */
13031 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
13032 if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
13033 scheduler = selectorOrScheduler;
13035 var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
13036 var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
13037 return function (source) { return multicast_1.multicast(function () { return subject; }, selector)(source); };
13039 exports.publishReplay = publishReplay;
13041 },{"../ReplaySubject":32,"./multicast":173}],179:[function(require,module,exports){
13043 var __extends = (this && this.__extends) || function (d, b) {
13044 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13045 function __() { this.constructor = d; }
13046 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13048 var Subscriber_1 = require('../Subscriber');
13049 function refCount() {
13050 return function refCountOperatorFunction(source) {
13051 return source.lift(new RefCountOperator(source));
13054 exports.refCount = refCount;
13055 var RefCountOperator = (function () {
13056 function RefCountOperator(connectable) {
13057 this.connectable = connectable;
13059 RefCountOperator.prototype.call = function (subscriber, source) {
13060 var connectable = this.connectable;
13061 connectable._refCount++;
13062 var refCounter = new RefCountSubscriber(subscriber, connectable);
13063 var subscription = source.subscribe(refCounter);
13064 if (!refCounter.closed) {
13065 refCounter.connection = connectable.connect();
13067 return subscription;
13069 return RefCountOperator;
13071 var RefCountSubscriber = (function (_super) {
13072 __extends(RefCountSubscriber, _super);
13073 function RefCountSubscriber(destination, connectable) {
13074 _super.call(this, destination);
13075 this.connectable = connectable;
13077 RefCountSubscriber.prototype._unsubscribe = function () {
13078 var connectable = this.connectable;
13079 if (!connectable) {
13080 this.connection = null;
13083 this.connectable = null;
13084 var refCount = connectable._refCount;
13085 if (refCount <= 0) {
13086 this.connection = null;
13089 connectable._refCount = refCount - 1;
13090 if (refCount > 1) {
13091 this.connection = null;
13095 // Compare the local RefCountSubscriber's connection Subscription to the
13096 // connection Subscription on the shared ConnectableObservable. In cases
13097 // where the ConnectableObservable source synchronously emits values, and
13098 // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
13099 // execution continues to here before the RefCountOperator has a chance to
13100 // supply the RefCountSubscriber with the shared connection Subscription.
13103 // Observable.range(0, 10)
13109 // In order to account for this case, RefCountSubscriber should only dispose
13110 // the ConnectableObservable's shared connection Subscription if the
13111 // connection Subscription exists, *and* either:
13112 // a. RefCountSubscriber doesn't have a reference to the shared connection
13113 // Subscription yet, or,
13114 // b. RefCountSubscriber's connection Subscription reference is identical
13115 // to the shared connection Subscription
13117 var connection = this.connection;
13118 var sharedConnection = connectable._connection;
13119 this.connection = null;
13120 if (sharedConnection && (!connection || sharedConnection === connection)) {
13121 sharedConnection.unsubscribe();
13124 return RefCountSubscriber;
13125 }(Subscriber_1.Subscriber));
13127 },{"../Subscriber":36}],180:[function(require,module,exports){
13129 var __extends = (this && this.__extends) || function (d, b) {
13130 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13131 function __() { this.constructor = d; }
13132 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13134 var Subscriber_1 = require('../Subscriber');
13136 * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
13137 * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
13138 * as a number parameter) rather than propagating the `error` call.
13140 * <img src="./img/retry.png" width="100%">
13142 * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
13143 * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
13144 * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
13145 * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
13146 * @param {number} count - Number of retry attempts before failing.
13147 * @return {Observable} The source Observable modified with the retry logic.
13149 * @owner Observable
13151 function retry(count) {
13152 if (count === void 0) { count = -1; }
13153 return function (source) { return source.lift(new RetryOperator(count, source)); };
13155 exports.retry = retry;
13156 var RetryOperator = (function () {
13157 function RetryOperator(count, source) {
13158 this.count = count;
13159 this.source = source;
13161 RetryOperator.prototype.call = function (subscriber, source) {
13162 return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
13164 return RetryOperator;
13167 * We need this JSDoc comment for affecting ESDoc.
13169 * @extends {Ignored}
13171 var RetrySubscriber = (function (_super) {
13172 __extends(RetrySubscriber, _super);
13173 function RetrySubscriber(destination, count, source) {
13174 _super.call(this, destination);
13175 this.count = count;
13176 this.source = source;
13178 RetrySubscriber.prototype.error = function (err) {
13179 if (!this.isStopped) {
13180 var _a = this, source = _a.source, count = _a.count;
13182 return _super.prototype.error.call(this, err);
13184 else if (count > -1) {
13185 this.count = count - 1;
13187 source.subscribe(this._unsubscribeAndRecycle());
13190 return RetrySubscriber;
13191 }(Subscriber_1.Subscriber));
13193 },{"../Subscriber":36}],181:[function(require,module,exports){
13195 var __extends = (this && this.__extends) || function (d, b) {
13196 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13197 function __() { this.constructor = d; }
13198 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13200 var OuterSubscriber_1 = require('../OuterSubscriber');
13201 var subscribeToResult_1 = require('../util/subscribeToResult');
13203 * Emits the most recently emitted value from the source Observable whenever
13204 * another Observable, the `notifier`, emits.
13206 * <span class="informal">It's like {@link sampleTime}, but samples whenever
13207 * the `notifier` Observable emits something.</span>
13209 * <img src="./img/sample.png" width="100%">
13211 * Whenever the `notifier` Observable emits a value or completes, `sample`
13212 * looks at the source Observable and emits whichever value it has most recently
13213 * emitted since the previous sampling, unless the source has not emitted
13214 * anything since the previous sampling. The `notifier` is subscribed to as soon
13215 * as the output Observable is subscribed.
13217 * @example <caption>On every click, sample the most recent "seconds" timer</caption>
13218 * var seconds = Rx.Observable.interval(1000);
13219 * var clicks = Rx.Observable.fromEvent(document, 'click');
13220 * var result = seconds.sample(clicks);
13221 * result.subscribe(x => console.log(x));
13223 * @see {@link audit}
13224 * @see {@link debounce}
13225 * @see {@link sampleTime}
13226 * @see {@link throttle}
13228 * @param {Observable<any>} notifier The Observable to use for sampling the
13229 * source Observable.
13230 * @return {Observable<T>} An Observable that emits the results of sampling the
13231 * values emitted by the source Observable whenever the notifier Observable
13232 * emits value or completes.
13234 * @owner Observable
13236 function sample(notifier) {
13237 return function (source) { return source.lift(new SampleOperator(notifier)); };
13239 exports.sample = sample;
13240 var SampleOperator = (function () {
13241 function SampleOperator(notifier) {
13242 this.notifier = notifier;
13244 SampleOperator.prototype.call = function (subscriber, source) {
13245 var sampleSubscriber = new SampleSubscriber(subscriber);
13246 var subscription = source.subscribe(sampleSubscriber);
13247 subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier));
13248 return subscription;
13250 return SampleOperator;
13253 * We need this JSDoc comment for affecting ESDoc.
13255 * @extends {Ignored}
13257 var SampleSubscriber = (function (_super) {
13258 __extends(SampleSubscriber, _super);
13259 function SampleSubscriber() {
13260 _super.apply(this, arguments);
13261 this.hasValue = false;
13263 SampleSubscriber.prototype._next = function (value) {
13264 this.value = value;
13265 this.hasValue = true;
13267 SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13270 SampleSubscriber.prototype.notifyComplete = function () {
13273 SampleSubscriber.prototype.emitValue = function () {
13274 if (this.hasValue) {
13275 this.hasValue = false;
13276 this.destination.next(this.value);
13279 return SampleSubscriber;
13280 }(OuterSubscriber_1.OuterSubscriber));
13282 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],182:[function(require,module,exports){
13284 var __extends = (this && this.__extends) || function (d, b) {
13285 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13286 function __() { this.constructor = d; }
13287 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13289 var Subscriber_1 = require('../Subscriber');
13290 /* tslint:enable:max-line-length */
13292 * Applies an accumulator function over the source Observable, and returns each
13293 * intermediate result, with an optional seed value.
13295 * <span class="informal">It's like {@link reduce}, but emits the current
13296 * accumulation whenever the source emits a value.</span>
13298 * <img src="./img/scan.png" width="100%">
13300 * Combines together all values emitted on the source, using an accumulator
13301 * function that knows how to join a new source value into the accumulation from
13302 * the past. Is similar to {@link reduce}, but emits the intermediate
13305 * Returns an Observable that applies a specified `accumulator` function to each
13306 * item emitted by the source Observable. If a `seed` value is specified, then
13307 * that value will be used as the initial value for the accumulator. If no seed
13308 * value is specified, the first item of the source is used as the seed.
13310 * @example <caption>Count the number of click events</caption>
13311 * var clicks = Rx.Observable.fromEvent(document, 'click');
13312 * var ones = clicks.mapTo(1);
13314 * var count = ones.scan((acc, one) => acc + one, seed);
13315 * count.subscribe(x => console.log(x));
13317 * @see {@link expand}
13318 * @see {@link mergeScan}
13319 * @see {@link reduce}
13321 * @param {function(acc: R, value: T, index: number): R} accumulator
13322 * The accumulator function called on each source value.
13323 * @param {T|R} [seed] The initial accumulation value.
13324 * @return {Observable<R>} An observable of the accumulated values.
13326 * @owner Observable
13328 function scan(accumulator, seed) {
13329 var hasSeed = false;
13330 // providing a seed of `undefined` *should* be valid and trigger
13331 // hasSeed! so don't use `seed !== undefined` checks!
13332 // For this reason, we have to check it here at the original call site
13333 // otherwise inside Operator/Subscriber we won't know if `undefined`
13334 // means they didn't provide anything or if they literally provided `undefined`
13335 if (arguments.length >= 2) {
13338 return function scanOperatorFunction(source) {
13339 return source.lift(new ScanOperator(accumulator, seed, hasSeed));
13342 exports.scan = scan;
13343 var ScanOperator = (function () {
13344 function ScanOperator(accumulator, seed, hasSeed) {
13345 if (hasSeed === void 0) { hasSeed = false; }
13346 this.accumulator = accumulator;
13348 this.hasSeed = hasSeed;
13350 ScanOperator.prototype.call = function (subscriber, source) {
13351 return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
13353 return ScanOperator;
13356 * We need this JSDoc comment for affecting ESDoc.
13358 * @extends {Ignored}
13360 var ScanSubscriber = (function (_super) {
13361 __extends(ScanSubscriber, _super);
13362 function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
13363 _super.call(this, destination);
13364 this.accumulator = accumulator;
13365 this._seed = _seed;
13366 this.hasSeed = hasSeed;
13369 Object.defineProperty(ScanSubscriber.prototype, "seed", {
13373 set: function (value) {
13374 this.hasSeed = true;
13375 this._seed = value;
13380 ScanSubscriber.prototype._next = function (value) {
13381 if (!this.hasSeed) {
13383 this.destination.next(value);
13386 return this._tryNext(value);
13389 ScanSubscriber.prototype._tryNext = function (value) {
13390 var index = this.index++;
13393 result = this.accumulator(this.seed, value, index);
13396 this.destination.error(err);
13398 this.seed = result;
13399 this.destination.next(result);
13401 return ScanSubscriber;
13402 }(Subscriber_1.Subscriber));
13404 },{"../Subscriber":36}],183:[function(require,module,exports){
13406 var multicast_1 = require('./multicast');
13407 var refCount_1 = require('./refCount');
13408 var Subject_1 = require('../Subject');
13409 function shareSubjectFactory() {
13410 return new Subject_1.Subject();
13413 * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
13414 * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
13415 * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
13416 * This is an alias for .multicast(() => new Subject()).refCount().
13418 * <img src="./img/share.png" width="100%">
13420 * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
13422 * @owner Observable
13425 return function (source) { return refCount_1.refCount()(multicast_1.multicast(shareSubjectFactory)(source)); };
13427 exports.share = share;
13430 },{"../Subject":34,"./multicast":173,"./refCount":179}],184:[function(require,module,exports){
13432 var __extends = (this && this.__extends) || function (d, b) {
13433 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13434 function __() { this.constructor = d; }
13435 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13437 var Subscriber_1 = require('../Subscriber');
13439 * Returns an Observable that skips the first `count` items emitted by the source Observable.
13441 * <img src="./img/skip.png" width="100%">
13443 * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
13444 * @return {Observable} An Observable that skips values emitted by the source Observable.
13447 * @owner Observable
13449 function skip(count) {
13450 return function (source) { return source.lift(new SkipOperator(count)); };
13452 exports.skip = skip;
13453 var SkipOperator = (function () {
13454 function SkipOperator(total) {
13455 this.total = total;
13457 SkipOperator.prototype.call = function (subscriber, source) {
13458 return source.subscribe(new SkipSubscriber(subscriber, this.total));
13460 return SkipOperator;
13463 * We need this JSDoc comment for affecting ESDoc.
13465 * @extends {Ignored}
13467 var SkipSubscriber = (function (_super) {
13468 __extends(SkipSubscriber, _super);
13469 function SkipSubscriber(destination, total) {
13470 _super.call(this, destination);
13471 this.total = total;
13474 SkipSubscriber.prototype._next = function (x) {
13475 if (++this.count > this.total) {
13476 this.destination.next(x);
13479 return SkipSubscriber;
13480 }(Subscriber_1.Subscriber));
13482 },{"../Subscriber":36}],185:[function(require,module,exports){
13484 var __extends = (this && this.__extends) || function (d, b) {
13485 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13486 function __() { this.constructor = d; }
13487 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13489 var OuterSubscriber_1 = require('../OuterSubscriber');
13490 var subscribeToResult_1 = require('../util/subscribeToResult');
13492 * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
13494 * <img src="./img/skipUntil.png" width="100%">
13496 * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
13497 * be mirrored by the resulting Observable.
13498 * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
13499 * an item, then emits the remaining items.
13500 * @method skipUntil
13501 * @owner Observable
13503 function skipUntil(notifier) {
13504 return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
13506 exports.skipUntil = skipUntil;
13507 var SkipUntilOperator = (function () {
13508 function SkipUntilOperator(notifier) {
13509 this.notifier = notifier;
13511 SkipUntilOperator.prototype.call = function (subscriber, source) {
13512 return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
13514 return SkipUntilOperator;
13517 * We need this JSDoc comment for affecting ESDoc.
13519 * @extends {Ignored}
13521 var SkipUntilSubscriber = (function (_super) {
13522 __extends(SkipUntilSubscriber, _super);
13523 function SkipUntilSubscriber(destination, notifier) {
13524 _super.call(this, destination);
13525 this.hasValue = false;
13526 this.isInnerStopped = false;
13527 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
13529 SkipUntilSubscriber.prototype._next = function (value) {
13530 if (this.hasValue) {
13531 _super.prototype._next.call(this, value);
13534 SkipUntilSubscriber.prototype._complete = function () {
13535 if (this.isInnerStopped) {
13536 _super.prototype._complete.call(this);
13539 this.unsubscribe();
13542 SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13543 this.hasValue = true;
13545 SkipUntilSubscriber.prototype.notifyComplete = function () {
13546 this.isInnerStopped = true;
13547 if (this.isStopped) {
13548 _super.prototype._complete.call(this);
13551 return SkipUntilSubscriber;
13552 }(OuterSubscriber_1.OuterSubscriber));
13554 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],186:[function(require,module,exports){
13556 var __extends = (this && this.__extends) || function (d, b) {
13557 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13558 function __() { this.constructor = d; }
13559 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13561 var Subscriber_1 = require('../Subscriber');
13563 * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
13564 * true, but emits all further source items as soon as the condition becomes false.
13566 * <img src="./img/skipWhile.png" width="100%">
13568 * @param {Function} predicate - A function to test each item emitted from the source Observable.
13569 * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
13570 * specified predicate becomes false.
13571 * @method skipWhile
13572 * @owner Observable
13574 function skipWhile(predicate) {
13575 return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
13577 exports.skipWhile = skipWhile;
13578 var SkipWhileOperator = (function () {
13579 function SkipWhileOperator(predicate) {
13580 this.predicate = predicate;
13582 SkipWhileOperator.prototype.call = function (subscriber, source) {
13583 return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
13585 return SkipWhileOperator;
13588 * We need this JSDoc comment for affecting ESDoc.
13590 * @extends {Ignored}
13592 var SkipWhileSubscriber = (function (_super) {
13593 __extends(SkipWhileSubscriber, _super);
13594 function SkipWhileSubscriber(destination, predicate) {
13595 _super.call(this, destination);
13596 this.predicate = predicate;
13597 this.skipping = true;
13600 SkipWhileSubscriber.prototype._next = function (value) {
13601 var destination = this.destination;
13602 if (this.skipping) {
13603 this.tryCallPredicate(value);
13605 if (!this.skipping) {
13606 destination.next(value);
13609 SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
13611 var result = this.predicate(value, this.index++);
13612 this.skipping = Boolean(result);
13615 this.destination.error(err);
13618 return SkipWhileSubscriber;
13619 }(Subscriber_1.Subscriber));
13621 },{"../Subscriber":36}],187:[function(require,module,exports){
13623 var ArrayObservable_1 = require('../observable/ArrayObservable');
13624 var ScalarObservable_1 = require('../observable/ScalarObservable');
13625 var EmptyObservable_1 = require('../observable/EmptyObservable');
13626 var concat_1 = require('../observable/concat');
13627 var isScheduler_1 = require('../util/isScheduler');
13628 /* tslint:enable:max-line-length */
13630 * Returns an Observable that emits the items you specify as arguments before it begins to emit
13631 * items emitted by the source Observable.
13633 * <img src="./img/startWith.png" width="100%">
13635 * @param {...T} values - Items you want the modified Observable to emit first.
13636 * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
13637 * the emissions of the `next` notifications.
13638 * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
13639 * emitted by the source Observable.
13640 * @method startWith
13641 * @owner Observable
13643 function startWith() {
13645 for (var _i = 0; _i < arguments.length; _i++) {
13646 array[_i - 0] = arguments[_i];
13648 return function (source) {
13649 var scheduler = array[array.length - 1];
13650 if (isScheduler_1.isScheduler(scheduler)) {
13656 var len = array.length;
13658 return concat_1.concat(new ScalarObservable_1.ScalarObservable(array[0], scheduler), source);
13660 else if (len > 1) {
13661 return concat_1.concat(new ArrayObservable_1.ArrayObservable(array, scheduler), source);
13664 return concat_1.concat(new EmptyObservable_1.EmptyObservable(scheduler), source);
13668 exports.startWith = startWith;
13670 },{"../observable/ArrayObservable":90,"../observable/EmptyObservable":93,"../observable/ScalarObservable":99,"../observable/concat":102,"../util/isScheduler":224}],188:[function(require,module,exports){
13672 var __extends = (this && this.__extends) || function (d, b) {
13673 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13674 function __() { this.constructor = d; }
13675 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13677 var OuterSubscriber_1 = require('../OuterSubscriber');
13678 var subscribeToResult_1 = require('../util/subscribeToResult');
13679 /* tslint:enable:max-line-length */
13681 * Projects each source value to an Observable which is merged in the output
13682 * Observable, emitting values only from the most recently projected Observable.
13684 * <span class="informal">Maps each value to an Observable, then flattens all of
13685 * these inner Observables using {@link switch}.</span>
13687 * <img src="./img/switchMap.png" width="100%">
13689 * Returns an Observable that emits items based on applying a function that you
13690 * supply to each item emitted by the source Observable, where that function
13691 * returns an (so-called "inner") Observable. Each time it observes one of these
13692 * inner Observables, the output Observable begins emitting the items emitted by
13693 * that inner Observable. When a new inner Observable is emitted, `switchMap`
13694 * stops emitting items from the earlier-emitted inner Observable and begins
13695 * emitting items from the new one. It continues to behave like this for
13696 * subsequent inner Observables.
13698 * @example <caption>Rerun an interval Observable on every click event</caption>
13699 * var clicks = Rx.Observable.fromEvent(document, 'click');
13700 * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
13701 * result.subscribe(x => console.log(x));
13703 * @see {@link concatMap}
13704 * @see {@link exhaustMap}
13705 * @see {@link mergeMap}
13706 * @see {@link switch}
13707 * @see {@link switchMapTo}
13709 * @param {function(value: T, ?index: number): ObservableInput} project A function
13710 * that, when applied to an item emitted by the source Observable, returns an
13712 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
13713 * A function to produce the value on the output Observable based on the values
13714 * and the indices of the source (outer) emission and the inner Observable
13715 * emission. The arguments passed to this function are:
13716 * - `outerValue`: the value that came from the source
13717 * - `innerValue`: the value that came from the projected Observable
13718 * - `outerIndex`: the "index" of the value that came from the source
13719 * - `innerIndex`: the "index" of the value from the projected Observable
13720 * @return {Observable} An Observable that emits the result of applying the
13721 * projection function (and the optional `resultSelector`) to each item emitted
13722 * by the source Observable and taking only the values from the most recently
13723 * projected inner Observable.
13724 * @method switchMap
13725 * @owner Observable
13727 function switchMap(project, resultSelector) {
13728 return function switchMapOperatorFunction(source) {
13729 return source.lift(new SwitchMapOperator(project, resultSelector));
13732 exports.switchMap = switchMap;
13733 var SwitchMapOperator = (function () {
13734 function SwitchMapOperator(project, resultSelector) {
13735 this.project = project;
13736 this.resultSelector = resultSelector;
13738 SwitchMapOperator.prototype.call = function (subscriber, source) {
13739 return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
13741 return SwitchMapOperator;
13744 * We need this JSDoc comment for affecting ESDoc.
13746 * @extends {Ignored}
13748 var SwitchMapSubscriber = (function (_super) {
13749 __extends(SwitchMapSubscriber, _super);
13750 function SwitchMapSubscriber(destination, project, resultSelector) {
13751 _super.call(this, destination);
13752 this.project = project;
13753 this.resultSelector = resultSelector;
13756 SwitchMapSubscriber.prototype._next = function (value) {
13758 var index = this.index++;
13760 result = this.project(value, index);
13763 this.destination.error(error);
13766 this._innerSub(result, value, index);
13768 SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
13769 var innerSubscription = this.innerSubscription;
13770 if (innerSubscription) {
13771 innerSubscription.unsubscribe();
13773 this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
13775 SwitchMapSubscriber.prototype._complete = function () {
13776 var innerSubscription = this.innerSubscription;
13777 if (!innerSubscription || innerSubscription.closed) {
13778 _super.prototype._complete.call(this);
13781 SwitchMapSubscriber.prototype._unsubscribe = function () {
13782 this.innerSubscription = null;
13784 SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
13785 this.remove(innerSub);
13786 this.innerSubscription = null;
13787 if (this.isStopped) {
13788 _super.prototype._complete.call(this);
13791 SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13792 if (this.resultSelector) {
13793 this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
13796 this.destination.next(innerValue);
13799 SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
13802 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
13805 this.destination.error(err);
13808 this.destination.next(result);
13810 return SwitchMapSubscriber;
13811 }(OuterSubscriber_1.OuterSubscriber));
13813 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],189:[function(require,module,exports){
13815 var __extends = (this && this.__extends) || function (d, b) {
13816 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13817 function __() { this.constructor = d; }
13818 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13820 var Subscriber_1 = require('../Subscriber');
13821 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
13822 var EmptyObservable_1 = require('../observable/EmptyObservable');
13824 * Emits only the first `count` values emitted by the source Observable.
13826 * <span class="informal">Takes the first `count` values from the source, then
13827 * completes.</span>
13829 * <img src="./img/take.png" width="100%">
13831 * `take` returns an Observable that emits only the first `count` values emitted
13832 * by the source Observable. If the source emits fewer than `count` values then
13833 * all of its values are emitted. After that, it completes, regardless if the
13834 * source completes.
13836 * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
13837 * var interval = Rx.Observable.interval(1000);
13838 * var five = interval.take(5);
13839 * five.subscribe(x => console.log(x));
13841 * @see {@link takeLast}
13842 * @see {@link takeUntil}
13843 * @see {@link takeWhile}
13844 * @see {@link skip}
13846 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
13847 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
13849 * @param {number} count The maximum number of `next` values to emit.
13850 * @return {Observable<T>} An Observable that emits only the first `count`
13851 * values emitted by the source Observable, or all of the values from the source
13852 * if the source emits fewer than `count` values.
13854 * @owner Observable
13856 function take(count) {
13857 return function (source) {
13859 return new EmptyObservable_1.EmptyObservable();
13862 return source.lift(new TakeOperator(count));
13866 exports.take = take;
13867 var TakeOperator = (function () {
13868 function TakeOperator(total) {
13869 this.total = total;
13870 if (this.total < 0) {
13871 throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
13874 TakeOperator.prototype.call = function (subscriber, source) {
13875 return source.subscribe(new TakeSubscriber(subscriber, this.total));
13877 return TakeOperator;
13880 * We need this JSDoc comment for affecting ESDoc.
13882 * @extends {Ignored}
13884 var TakeSubscriber = (function (_super) {
13885 __extends(TakeSubscriber, _super);
13886 function TakeSubscriber(destination, total) {
13887 _super.call(this, destination);
13888 this.total = total;
13891 TakeSubscriber.prototype._next = function (value) {
13892 var total = this.total;
13893 var count = ++this.count;
13894 if (count <= total) {
13895 this.destination.next(value);
13896 if (count === total) {
13897 this.destination.complete();
13898 this.unsubscribe();
13902 return TakeSubscriber;
13903 }(Subscriber_1.Subscriber));
13905 },{"../Subscriber":36,"../observable/EmptyObservable":93,"../util/ArgumentOutOfRangeError":209}],190:[function(require,module,exports){
13907 var __extends = (this && this.__extends) || function (d, b) {
13908 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13909 function __() { this.constructor = d; }
13910 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13912 var OuterSubscriber_1 = require('../OuterSubscriber');
13913 var subscribeToResult_1 = require('../util/subscribeToResult');
13915 * Emits the values emitted by the source Observable until a `notifier`
13916 * Observable emits a value.
13918 * <span class="informal">Lets values pass until a second Observable,
13919 * `notifier`, emits something. Then, it completes.</span>
13921 * <img src="./img/takeUntil.png" width="100%">
13923 * `takeUntil` subscribes and begins mirroring the source Observable. It also
13924 * monitors a second Observable, `notifier` that you provide. If the `notifier`
13925 * emits a value or a complete notification, the output Observable stops
13926 * mirroring the source Observable and completes.
13928 * @example <caption>Tick every second until the first click happens</caption>
13929 * var interval = Rx.Observable.interval(1000);
13930 * var clicks = Rx.Observable.fromEvent(document, 'click');
13931 * var result = interval.takeUntil(clicks);
13932 * result.subscribe(x => console.log(x));
13934 * @see {@link take}
13935 * @see {@link takeLast}
13936 * @see {@link takeWhile}
13937 * @see {@link skip}
13939 * @param {Observable} notifier The Observable whose first emitted value will
13940 * cause the output Observable of `takeUntil` to stop emitting values from the
13941 * source Observable.
13942 * @return {Observable<T>} An Observable that emits the values from the source
13943 * Observable until such time as `notifier` emits its first value.
13944 * @method takeUntil
13945 * @owner Observable
13947 function takeUntil(notifier) {
13948 return function (source) { return source.lift(new TakeUntilOperator(notifier)); };
13950 exports.takeUntil = takeUntil;
13951 var TakeUntilOperator = (function () {
13952 function TakeUntilOperator(notifier) {
13953 this.notifier = notifier;
13955 TakeUntilOperator.prototype.call = function (subscriber, source) {
13956 return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
13958 return TakeUntilOperator;
13961 * We need this JSDoc comment for affecting ESDoc.
13963 * @extends {Ignored}
13965 var TakeUntilSubscriber = (function (_super) {
13966 __extends(TakeUntilSubscriber, _super);
13967 function TakeUntilSubscriber(destination, notifier) {
13968 _super.call(this, destination);
13969 this.notifier = notifier;
13970 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
13972 TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13975 TakeUntilSubscriber.prototype.notifyComplete = function () {
13978 return TakeUntilSubscriber;
13979 }(OuterSubscriber_1.OuterSubscriber));
13981 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],191:[function(require,module,exports){
13983 var __extends = (this && this.__extends) || function (d, b) {
13984 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13985 function __() { this.constructor = d; }
13986 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13988 var Subscriber_1 = require('../Subscriber');
13990 * Emits values emitted by the source Observable so long as each value satisfies
13991 * the given `predicate`, and then completes as soon as this `predicate` is not
13994 * <span class="informal">Takes values from the source only while they pass the
13995 * condition given. When the first value does not satisfy, it completes.</span>
13997 * <img src="./img/takeWhile.png" width="100%">
13999 * `takeWhile` subscribes and begins mirroring the source Observable. Each value
14000 * emitted on the source is given to the `predicate` function which returns a
14001 * boolean, representing a condition to be satisfied by the source values. The
14002 * output Observable emits the source values until such time as the `predicate`
14003 * returns false, at which point `takeWhile` stops mirroring the source
14004 * Observable and completes the output Observable.
14006 * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
14007 * var clicks = Rx.Observable.fromEvent(document, 'click');
14008 * var result = clicks.takeWhile(ev => ev.clientX > 200);
14009 * result.subscribe(x => console.log(x));
14011 * @see {@link take}
14012 * @see {@link takeLast}
14013 * @see {@link takeUntil}
14014 * @see {@link skip}
14016 * @param {function(value: T, index: number): boolean} predicate A function that
14017 * evaluates a value emitted by the source Observable and returns a boolean.
14018 * Also takes the (zero-based) index as the second argument.
14019 * @return {Observable<T>} An Observable that emits the values from the source
14020 * Observable so long as each value satisfies the condition defined by the
14021 * `predicate`, then completes.
14022 * @method takeWhile
14023 * @owner Observable
14025 function takeWhile(predicate) {
14026 return function (source) { return source.lift(new TakeWhileOperator(predicate)); };
14028 exports.takeWhile = takeWhile;
14029 var TakeWhileOperator = (function () {
14030 function TakeWhileOperator(predicate) {
14031 this.predicate = predicate;
14033 TakeWhileOperator.prototype.call = function (subscriber, source) {
14034 return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
14036 return TakeWhileOperator;
14039 * We need this JSDoc comment for affecting ESDoc.
14041 * @extends {Ignored}
14043 var TakeWhileSubscriber = (function (_super) {
14044 __extends(TakeWhileSubscriber, _super);
14045 function TakeWhileSubscriber(destination, predicate) {
14046 _super.call(this, destination);
14047 this.predicate = predicate;
14050 TakeWhileSubscriber.prototype._next = function (value) {
14051 var destination = this.destination;
14054 result = this.predicate(value, this.index++);
14057 destination.error(err);
14060 this.nextOrComplete(value, result);
14062 TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
14063 var destination = this.destination;
14064 if (Boolean(predicateResult)) {
14065 destination.next(value);
14068 destination.complete();
14071 return TakeWhileSubscriber;
14072 }(Subscriber_1.Subscriber));
14074 },{"../Subscriber":36}],192:[function(require,module,exports){
14076 var __extends = (this && this.__extends) || function (d, b) {
14077 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14078 function __() { this.constructor = d; }
14079 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14081 var Subscriber_1 = require('../Subscriber');
14082 /* tslint:enable:max-line-length */
14084 * Perform a side effect for every emission on the source Observable, but return
14085 * an Observable that is identical to the source.
14087 * <span class="informal">Intercepts each emission on the source and runs a
14088 * function, but returns an output which is identical to the source as long as errors don't occur.</span>
14090 * <img src="./img/do.png" width="100%">
14092 * Returns a mirrored Observable of the source Observable, but modified so that
14093 * the provided Observer is called to perform a side effect for every value,
14094 * error, and completion emitted by the source. Any errors that are thrown in
14095 * the aforementioned Observer or handlers are safely sent down the error path
14096 * of the output Observable.
14098 * This operator is useful for debugging your Observables for the correct values
14099 * or performing other side effects.
14101 * Note: this is different to a `subscribe` on the Observable. If the Observable
14102 * returned by `do` is not subscribed, the side effects specified by the
14103 * Observer will never happen. `do` therefore simply spies on existing
14104 * execution, it does not trigger an execution to happen like `subscribe` does.
14106 * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
14107 * var clicks = Rx.Observable.fromEvent(document, 'click');
14108 * var positions = clicks
14109 * .do(ev => console.log(ev))
14110 * .map(ev => ev.clientX);
14111 * positions.subscribe(x => console.log(x));
14114 * @see {@link subscribe}
14116 * @param {Observer|function} [nextOrObserver] A normal Observer object or a
14117 * callback for `next`.
14118 * @param {function} [error] Callback for errors in the source.
14119 * @param {function} [complete] Callback for the completion of the source.
14120 * @return {Observable} An Observable identical to the source, but runs the
14121 * specified Observer or callback(s) for each item.
14124 function tap(nextOrObserver, error, complete) {
14125 return function tapOperatorFunction(source) {
14126 return source.lift(new DoOperator(nextOrObserver, error, complete));
14130 var DoOperator = (function () {
14131 function DoOperator(nextOrObserver, error, complete) {
14132 this.nextOrObserver = nextOrObserver;
14133 this.error = error;
14134 this.complete = complete;
14136 DoOperator.prototype.call = function (subscriber, source) {
14137 return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
14142 * We need this JSDoc comment for affecting ESDoc.
14144 * @extends {Ignored}
14146 var DoSubscriber = (function (_super) {
14147 __extends(DoSubscriber, _super);
14148 function DoSubscriber(destination, nextOrObserver, error, complete) {
14149 _super.call(this, destination);
14150 var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
14151 safeSubscriber.syncErrorThrowable = true;
14152 this.add(safeSubscriber);
14153 this.safeSubscriber = safeSubscriber;
14155 DoSubscriber.prototype._next = function (value) {
14156 var safeSubscriber = this.safeSubscriber;
14157 safeSubscriber.next(value);
14158 if (safeSubscriber.syncErrorThrown) {
14159 this.destination.error(safeSubscriber.syncErrorValue);
14162 this.destination.next(value);
14165 DoSubscriber.prototype._error = function (err) {
14166 var safeSubscriber = this.safeSubscriber;
14167 safeSubscriber.error(err);
14168 if (safeSubscriber.syncErrorThrown) {
14169 this.destination.error(safeSubscriber.syncErrorValue);
14172 this.destination.error(err);
14175 DoSubscriber.prototype._complete = function () {
14176 var safeSubscriber = this.safeSubscriber;
14177 safeSubscriber.complete();
14178 if (safeSubscriber.syncErrorThrown) {
14179 this.destination.error(safeSubscriber.syncErrorValue);
14182 this.destination.complete();
14185 return DoSubscriber;
14186 }(Subscriber_1.Subscriber));
14188 },{"../Subscriber":36}],193:[function(require,module,exports){
14190 var __extends = (this && this.__extends) || function (d, b) {
14191 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14192 function __() { this.constructor = d; }
14193 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14195 var OuterSubscriber_1 = require('../OuterSubscriber');
14196 var subscribeToResult_1 = require('../util/subscribeToResult');
14197 exports.defaultThrottleConfig = {
14202 * Emits a value from the source Observable, then ignores subsequent source
14203 * values for a duration determined by another Observable, then repeats this
14206 * <span class="informal">It's like {@link throttleTime}, but the silencing
14207 * duration is determined by a second Observable.</span>
14209 * <img src="./img/throttle.png" width="100%">
14211 * `throttle` emits the source Observable values on the output Observable
14212 * when its internal timer is disabled, and ignores source values when the timer
14213 * is enabled. Initially, the timer is disabled. As soon as the first source
14214 * value arrives, it is forwarded to the output Observable, and then the timer
14215 * is enabled by calling the `durationSelector` function with the source value,
14216 * which returns the "duration" Observable. When the duration Observable emits a
14217 * value or completes, the timer is disabled, and this process repeats for the
14218 * next source value.
14220 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
14221 * var clicks = Rx.Observable.fromEvent(document, 'click');
14222 * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
14223 * result.subscribe(x => console.log(x));
14225 * @see {@link audit}
14226 * @see {@link debounce}
14227 * @see {@link delayWhen}
14228 * @see {@link sample}
14229 * @see {@link throttleTime}
14231 * @param {function(value: T): SubscribableOrPromise} durationSelector A function
14232 * that receives a value from the source Observable, for computing the silencing
14233 * duration for each source value, returned as an Observable or a Promise.
14234 * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
14235 * to `{ leading: true, trailing: false }`.
14236 * @return {Observable<T>} An Observable that performs the throttle operation to
14237 * limit the rate of emissions from the source.
14239 * @owner Observable
14241 function throttle(durationSelector, config) {
14242 if (config === void 0) { config = exports.defaultThrottleConfig; }
14243 return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
14245 exports.throttle = throttle;
14246 var ThrottleOperator = (function () {
14247 function ThrottleOperator(durationSelector, leading, trailing) {
14248 this.durationSelector = durationSelector;
14249 this.leading = leading;
14250 this.trailing = trailing;
14252 ThrottleOperator.prototype.call = function (subscriber, source) {
14253 return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
14255 return ThrottleOperator;
14258 * We need this JSDoc comment for affecting ESDoc
14260 * @extends {Ignored}
14262 var ThrottleSubscriber = (function (_super) {
14263 __extends(ThrottleSubscriber, _super);
14264 function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
14265 _super.call(this, destination);
14266 this.destination = destination;
14267 this.durationSelector = durationSelector;
14268 this._leading = _leading;
14269 this._trailing = _trailing;
14270 this._hasTrailingValue = false;
14272 ThrottleSubscriber.prototype._next = function (value) {
14273 if (this.throttled) {
14274 if (this._trailing) {
14275 this._hasTrailingValue = true;
14276 this._trailingValue = value;
14280 var duration = this.tryDurationSelector(value);
14282 this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration));
14284 if (this._leading) {
14285 this.destination.next(value);
14286 if (this._trailing) {
14287 this._hasTrailingValue = true;
14288 this._trailingValue = value;
14293 ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
14295 return this.durationSelector(value);
14298 this.destination.error(err);
14302 ThrottleSubscriber.prototype._unsubscribe = function () {
14303 var _a = this, throttled = _a.throttled, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue, _trailing = _a._trailing;
14304 this._trailingValue = null;
14305 this._hasTrailingValue = false;
14307 this.remove(throttled);
14308 this.throttled = null;
14309 throttled.unsubscribe();
14312 ThrottleSubscriber.prototype._sendTrailing = function () {
14313 var _a = this, destination = _a.destination, throttled = _a.throttled, _trailing = _a._trailing, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue;
14314 if (throttled && _trailing && _hasTrailingValue) {
14315 destination.next(_trailingValue);
14316 this._trailingValue = null;
14317 this._hasTrailingValue = false;
14320 ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14321 this._sendTrailing();
14322 this._unsubscribe();
14324 ThrottleSubscriber.prototype.notifyComplete = function () {
14325 this._sendTrailing();
14326 this._unsubscribe();
14328 return ThrottleSubscriber;
14329 }(OuterSubscriber_1.OuterSubscriber));
14331 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],194:[function(require,module,exports){
14333 var __extends = (this && this.__extends) || function (d, b) {
14334 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14335 function __() { this.constructor = d; }
14336 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14338 var Subscriber_1 = require('../Subscriber');
14339 var async_1 = require('../scheduler/async');
14340 var throttle_1 = require('./throttle');
14342 * Emits a value from the source Observable, then ignores subsequent source
14343 * values for `duration` milliseconds, then repeats this process.
14345 * <span class="informal">Lets a value pass, then ignores source values for the
14346 * next `duration` milliseconds.</span>
14348 * <img src="./img/throttleTime.png" width="100%">
14350 * `throttleTime` emits the source Observable values on the output Observable
14351 * when its internal timer is disabled, and ignores source values when the timer
14352 * is enabled. Initially, the timer is disabled. As soon as the first source
14353 * value arrives, it is forwarded to the output Observable, and then the timer
14354 * is enabled. After `duration` milliseconds (or the time unit determined
14355 * internally by the optional `scheduler`) has passed, the timer is disabled,
14356 * and this process repeats for the next source value. Optionally takes a
14357 * {@link IScheduler} for managing timers.
14359 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
14360 * var clicks = Rx.Observable.fromEvent(document, 'click');
14361 * var result = clicks.throttleTime(1000);
14362 * result.subscribe(x => console.log(x));
14364 * @see {@link auditTime}
14365 * @see {@link debounceTime}
14366 * @see {@link delay}
14367 * @see {@link sampleTime}
14368 * @see {@link throttle}
14370 * @param {number} duration Time to wait before emitting another value after
14371 * emitting the last value, measured in milliseconds or the time unit determined
14372 * internally by the optional `scheduler`.
14373 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
14374 * managing the timers that handle the throttling.
14375 * @return {Observable<T>} An Observable that performs the throttle operation to
14376 * limit the rate of emissions from the source.
14377 * @method throttleTime
14378 * @owner Observable
14380 function throttleTime(duration, scheduler, config) {
14381 if (scheduler === void 0) { scheduler = async_1.async; }
14382 if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
14383 return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
14385 exports.throttleTime = throttleTime;
14386 var ThrottleTimeOperator = (function () {
14387 function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
14388 this.duration = duration;
14389 this.scheduler = scheduler;
14390 this.leading = leading;
14391 this.trailing = trailing;
14393 ThrottleTimeOperator.prototype.call = function (subscriber, source) {
14394 return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
14396 return ThrottleTimeOperator;
14399 * We need this JSDoc comment for affecting ESDoc.
14401 * @extends {Ignored}
14403 var ThrottleTimeSubscriber = (function (_super) {
14404 __extends(ThrottleTimeSubscriber, _super);
14405 function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
14406 _super.call(this, destination);
14407 this.duration = duration;
14408 this.scheduler = scheduler;
14409 this.leading = leading;
14410 this.trailing = trailing;
14411 this._hasTrailingValue = false;
14412 this._trailingValue = null;
14414 ThrottleTimeSubscriber.prototype._next = function (value) {
14415 if (this.throttled) {
14416 if (this.trailing) {
14417 this._trailingValue = value;
14418 this._hasTrailingValue = true;
14422 this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
14423 if (this.leading) {
14424 this.destination.next(value);
14428 ThrottleTimeSubscriber.prototype.clearThrottle = function () {
14429 var throttled = this.throttled;
14431 if (this.trailing && this._hasTrailingValue) {
14432 this.destination.next(this._trailingValue);
14433 this._trailingValue = null;
14434 this._hasTrailingValue = false;
14436 throttled.unsubscribe();
14437 this.remove(throttled);
14438 this.throttled = null;
14441 return ThrottleTimeSubscriber;
14442 }(Subscriber_1.Subscriber));
14443 function dispatchNext(arg) {
14444 var subscriber = arg.subscriber;
14445 subscriber.clearThrottle();
14448 },{"../Subscriber":36,"../scheduler/async":203,"./throttle":193}],195:[function(require,module,exports){
14450 var __extends = (this && this.__extends) || function (d, b) {
14451 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14452 function __() { this.constructor = d; }
14453 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14455 var async_1 = require('../scheduler/async');
14456 var isDate_1 = require('../util/isDate');
14457 var Subscriber_1 = require('../Subscriber');
14458 var TimeoutError_1 = require('../util/TimeoutError');
14461 * Errors if Observable does not emit a value in given time span.
14463 * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
14465 * <img src="./img/timeout.png" width="100%">
14467 * `timeout` operator accepts as an argument either a number or a Date.
14469 * If number was provided, it returns an Observable that behaves like a source
14470 * Observable, unless there is a period of time where there is no value emitted.
14471 * So if you provide `100` as argument and first value comes after 50ms from
14472 * the moment of subscription, this value will be simply re-emitted by the resulting
14473 * Observable. If however after that 100ms passes without a second value being emitted,
14474 * stream will end with an error and source Observable will be unsubscribed.
14475 * These checks are performed throughout whole lifecycle of Observable - from the moment
14476 * it was subscribed to, until it completes or errors itself. Thus every value must be
14477 * emitted within specified period since previous value.
14479 * If provided argument was Date, returned Observable behaves differently. It throws
14480 * if Observable did not complete before provided Date. This means that periods between
14481 * emission of particular values do not matter in this case. If Observable did not complete
14482 * before provided Date, source Observable will be unsubscribed. Other than that, resulting
14483 * stream behaves just as source Observable.
14485 * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
14486 * when returned Observable will check if source stream emitted value or completed.
14488 * @example <caption>Check if ticks are emitted within certain timespan</caption>
14489 * const seconds = Rx.Observable.interval(1000);
14491 * seconds.timeout(1100) // Let's use bigger timespan to be safe,
14492 * // since `interval` might fire a bit later then scheduled.
14494 * value => console.log(value), // Will emit numbers just as regular `interval` would.
14495 * err => console.log(err) // Will never be called.
14498 * seconds.timeout(900).subscribe(
14499 * value => console.log(value), // Will never be called.
14500 * err => console.log(err) // Will emit error before even first value is emitted,
14501 * // since it did not arrive within 900ms period.
14504 * @example <caption>Use Date to check if Observable completed</caption>
14505 * const seconds = Rx.Observable.interval(1000);
14507 * seconds.timeout(new Date("December 17, 2020 03:24:00"))
14509 * value => console.log(value), // Will emit values as regular `interval` would
14510 * // until December 17, 2020 at 03:24:00.
14511 * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
14512 * // since Observable did not complete by then.
14515 * @see {@link timeoutWith}
14517 * @param {number|Date} due Number specifying period within which Observable must emit values
14518 * or Date specifying before when Observable should complete
14519 * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
14520 * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
14522 * @owner Observable
14524 function timeout(due, scheduler) {
14525 if (scheduler === void 0) { scheduler = async_1.async; }
14526 var absoluteTimeout = isDate_1.isDate(due);
14527 var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
14528 return function (source) { return source.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new TimeoutError_1.TimeoutError())); };
14530 exports.timeout = timeout;
14531 var TimeoutOperator = (function () {
14532 function TimeoutOperator(waitFor, absoluteTimeout, scheduler, errorInstance) {
14533 this.waitFor = waitFor;
14534 this.absoluteTimeout = absoluteTimeout;
14535 this.scheduler = scheduler;
14536 this.errorInstance = errorInstance;
14538 TimeoutOperator.prototype.call = function (subscriber, source) {
14539 return source.subscribe(new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.scheduler, this.errorInstance));
14541 return TimeoutOperator;
14544 * We need this JSDoc comment for affecting ESDoc.
14546 * @extends {Ignored}
14548 var TimeoutSubscriber = (function (_super) {
14549 __extends(TimeoutSubscriber, _super);
14550 function TimeoutSubscriber(destination, absoluteTimeout, waitFor, scheduler, errorInstance) {
14551 _super.call(this, destination);
14552 this.absoluteTimeout = absoluteTimeout;
14553 this.waitFor = waitFor;
14554 this.scheduler = scheduler;
14555 this.errorInstance = errorInstance;
14556 this.action = null;
14557 this.scheduleTimeout();
14559 TimeoutSubscriber.dispatchTimeout = function (subscriber) {
14560 subscriber.error(subscriber.errorInstance);
14562 TimeoutSubscriber.prototype.scheduleTimeout = function () {
14563 var action = this.action;
14565 // Recycle the action if we've already scheduled one. All the production
14566 // Scheduler Actions mutate their state/delay time and return themeselves.
14567 // VirtualActions are immutable, so they create and return a clone. In this
14568 // case, we need to set the action reference to the most recent VirtualAction,
14569 // to ensure that's the one we clone from next time.
14570 this.action = action.schedule(this, this.waitFor);
14573 this.add(this.action = this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, this));
14576 TimeoutSubscriber.prototype._next = function (value) {
14577 if (!this.absoluteTimeout) {
14578 this.scheduleTimeout();
14580 _super.prototype._next.call(this, value);
14582 TimeoutSubscriber.prototype._unsubscribe = function () {
14583 this.action = null;
14584 this.scheduler = null;
14585 this.errorInstance = null;
14587 return TimeoutSubscriber;
14588 }(Subscriber_1.Subscriber));
14590 },{"../Subscriber":36,"../scheduler/async":203,"../util/TimeoutError":213,"../util/isDate":219}],196:[function(require,module,exports){
14592 var __extends = (this && this.__extends) || function (d, b) {
14593 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14594 function __() { this.constructor = d; }
14595 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14597 var OuterSubscriber_1 = require('../OuterSubscriber');
14598 var subscribeToResult_1 = require('../util/subscribeToResult');
14599 /* tslint:enable:max-line-length */
14601 * Combines the source Observable with other Observables to create an Observable
14602 * whose values are calculated from the latest values of each, only when the
14605 * <span class="informal">Whenever the source Observable emits a value, it
14606 * computes a formula using that value plus the latest values from other input
14607 * Observables, then emits the output of that formula.</span>
14609 * <img src="./img/withLatestFrom.png" width="100%">
14611 * `withLatestFrom` combines each value from the source Observable (the
14612 * instance) with the latest values from the other input Observables only when
14613 * the source emits a value, optionally using a `project` function to determine
14614 * the value to be emitted on the output Observable. All input Observables must
14615 * emit at least one value before the output Observable will emit a value.
14617 * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
14618 * var clicks = Rx.Observable.fromEvent(document, 'click');
14619 * var timer = Rx.Observable.interval(1000);
14620 * var result = clicks.withLatestFrom(timer);
14621 * result.subscribe(x => console.log(x));
14623 * @see {@link combineLatest}
14625 * @param {ObservableInput} other An input Observable to combine with the source
14626 * Observable. More than one input Observables may be given as argument.
14627 * @param {Function} [project] Projection function for combining values
14628 * together. Receives all values in order of the Observables passed, where the
14629 * first parameter is a value from the source Observable. (e.g.
14630 * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
14631 * passed, arrays will be emitted on the output Observable.
14632 * @return {Observable} An Observable of projected values from the most recent
14633 * values from each input Observable, or an array of the most recent values from
14634 * each input Observable.
14635 * @method withLatestFrom
14636 * @owner Observable
14638 function withLatestFrom() {
14640 for (var _i = 0; _i < arguments.length; _i++) {
14641 args[_i - 0] = arguments[_i];
14643 return function (source) {
14645 if (typeof args[args.length - 1] === 'function') {
14646 project = args.pop();
14648 var observables = args;
14649 return source.lift(new WithLatestFromOperator(observables, project));
14652 exports.withLatestFrom = withLatestFrom;
14653 var WithLatestFromOperator = (function () {
14654 function WithLatestFromOperator(observables, project) {
14655 this.observables = observables;
14656 this.project = project;
14658 WithLatestFromOperator.prototype.call = function (subscriber, source) {
14659 return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
14661 return WithLatestFromOperator;
14664 * We need this JSDoc comment for affecting ESDoc.
14666 * @extends {Ignored}
14668 var WithLatestFromSubscriber = (function (_super) {
14669 __extends(WithLatestFromSubscriber, _super);
14670 function WithLatestFromSubscriber(destination, observables, project) {
14671 _super.call(this, destination);
14672 this.observables = observables;
14673 this.project = project;
14674 this.toRespond = [];
14675 var len = observables.length;
14676 this.values = new Array(len);
14677 for (var i = 0; i < len; i++) {
14678 this.toRespond.push(i);
14680 for (var i = 0; i < len; i++) {
14681 var observable = observables[i];
14682 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
14685 WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14686 this.values[outerIndex] = innerValue;
14687 var toRespond = this.toRespond;
14688 if (toRespond.length > 0) {
14689 var found = toRespond.indexOf(outerIndex);
14690 if (found !== -1) {
14691 toRespond.splice(found, 1);
14695 WithLatestFromSubscriber.prototype.notifyComplete = function () {
14698 WithLatestFromSubscriber.prototype._next = function (value) {
14699 if (this.toRespond.length === 0) {
14700 var args = [value].concat(this.values);
14701 if (this.project) {
14702 this._tryProject(args);
14705 this.destination.next(args);
14709 WithLatestFromSubscriber.prototype._tryProject = function (args) {
14712 result = this.project.apply(this, args);
14715 this.destination.error(err);
14718 this.destination.next(result);
14720 return WithLatestFromSubscriber;
14721 }(OuterSubscriber_1.OuterSubscriber));
14723 },{"../OuterSubscriber":31,"../util/subscribeToResult":228}],197:[function(require,module,exports){
14725 var __extends = (this && this.__extends) || function (d, b) {
14726 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14727 function __() { this.constructor = d; }
14728 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14730 var ArrayObservable_1 = require('../observable/ArrayObservable');
14731 var isArray_1 = require('../util/isArray');
14732 var Subscriber_1 = require('../Subscriber');
14733 var OuterSubscriber_1 = require('../OuterSubscriber');
14734 var subscribeToResult_1 = require('../util/subscribeToResult');
14735 var iterator_1 = require('../symbol/iterator');
14736 /* tslint:enable:max-line-length */
14738 * @param observables
14739 * @return {Observable<R>}
14741 * @owner Observable
14744 var observables = [];
14745 for (var _i = 0; _i < arguments.length; _i++) {
14746 observables[_i - 0] = arguments[_i];
14748 return function zipOperatorFunction(source) {
14749 return source.lift.call(zipStatic.apply(void 0, [source].concat(observables)));
14753 /* tslint:enable:max-line-length */
14755 * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
14756 * of its input Observables.
14758 * If the latest parameter is a function, this function is used to compute the created value from the input values.
14759 * Otherwise, an array of the input values is returned.
14761 * @example <caption>Combine age and name from different sources</caption>
14763 * let age$ = Observable.of<number>(27, 25, 29);
14764 * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
14765 * let isDev$ = Observable.of<boolean>(true, true, false);
14771 * (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
14772 * .subscribe(x => console.log(x));
14775 * // { age: 27, name: 'Foo', isDev: true }
14776 * // { age: 25, name: 'Bar', isDev: true }
14777 * // { age: 29, name: 'Beer', isDev: false }
14779 * @param observables
14780 * @return {Observable<R>}
14783 * @owner Observable
14785 function zipStatic() {
14786 var observables = [];
14787 for (var _i = 0; _i < arguments.length; _i++) {
14788 observables[_i - 0] = arguments[_i];
14790 var project = observables[observables.length - 1];
14791 if (typeof project === 'function') {
14794 return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
14796 exports.zipStatic = zipStatic;
14797 var ZipOperator = (function () {
14798 function ZipOperator(project) {
14799 this.project = project;
14801 ZipOperator.prototype.call = function (subscriber, source) {
14802 return source.subscribe(new ZipSubscriber(subscriber, this.project));
14804 return ZipOperator;
14806 exports.ZipOperator = ZipOperator;
14808 * We need this JSDoc comment for affecting ESDoc.
14810 * @extends {Ignored}
14812 var ZipSubscriber = (function (_super) {
14813 __extends(ZipSubscriber, _super);
14814 function ZipSubscriber(destination, project, values) {
14815 if (values === void 0) { values = Object.create(null); }
14816 _super.call(this, destination);
14817 this.iterators = [];
14819 this.project = (typeof project === 'function') ? project : null;
14820 this.values = values;
14822 ZipSubscriber.prototype._next = function (value) {
14823 var iterators = this.iterators;
14824 if (isArray_1.isArray(value)) {
14825 iterators.push(new StaticArrayIterator(value));
14827 else if (typeof value[iterator_1.iterator] === 'function') {
14828 iterators.push(new StaticIterator(value[iterator_1.iterator]()));
14831 iterators.push(new ZipBufferIterator(this.destination, this, value));
14834 ZipSubscriber.prototype._complete = function () {
14835 var iterators = this.iterators;
14836 var len = iterators.length;
14838 this.destination.complete();
14842 for (var i = 0; i < len; i++) {
14843 var iterator = iterators[i];
14844 if (iterator.stillUnsubscribed) {
14845 this.add(iterator.subscribe(iterator, i));
14848 this.active--; // not an observable
14852 ZipSubscriber.prototype.notifyInactive = function () {
14854 if (this.active === 0) {
14855 this.destination.complete();
14858 ZipSubscriber.prototype.checkIterators = function () {
14859 var iterators = this.iterators;
14860 var len = iterators.length;
14861 var destination = this.destination;
14862 // abort if not all of them have values
14863 for (var i = 0; i < len; i++) {
14864 var iterator = iterators[i];
14865 if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
14869 var shouldComplete = false;
14871 for (var i = 0; i < len; i++) {
14872 var iterator = iterators[i];
14873 var result = iterator.next();
14874 // check to see if it's completed now that you've gotten
14876 if (iterator.hasCompleted()) {
14877 shouldComplete = true;
14880 destination.complete();
14883 args.push(result.value);
14885 if (this.project) {
14886 this._tryProject(args);
14889 destination.next(args);
14891 if (shouldComplete) {
14892 destination.complete();
14895 ZipSubscriber.prototype._tryProject = function (args) {
14898 result = this.project.apply(this, args);
14901 this.destination.error(err);
14904 this.destination.next(result);
14906 return ZipSubscriber;
14907 }(Subscriber_1.Subscriber));
14908 exports.ZipSubscriber = ZipSubscriber;
14909 var StaticIterator = (function () {
14910 function StaticIterator(iterator) {
14911 this.iterator = iterator;
14912 this.nextResult = iterator.next();
14914 StaticIterator.prototype.hasValue = function () {
14917 StaticIterator.prototype.next = function () {
14918 var result = this.nextResult;
14919 this.nextResult = this.iterator.next();
14922 StaticIterator.prototype.hasCompleted = function () {
14923 var nextResult = this.nextResult;
14924 return nextResult && nextResult.done;
14926 return StaticIterator;
14928 var StaticArrayIterator = (function () {
14929 function StaticArrayIterator(array) {
14930 this.array = array;
14933 this.length = array.length;
14935 StaticArrayIterator.prototype[iterator_1.iterator] = function () {
14938 StaticArrayIterator.prototype.next = function (value) {
14939 var i = this.index++;
14940 var array = this.array;
14941 return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
14943 StaticArrayIterator.prototype.hasValue = function () {
14944 return this.array.length > this.index;
14946 StaticArrayIterator.prototype.hasCompleted = function () {
14947 return this.array.length === this.index;
14949 return StaticArrayIterator;
14952 * We need this JSDoc comment for affecting ESDoc.
14954 * @extends {Ignored}
14956 var ZipBufferIterator = (function (_super) {
14957 __extends(ZipBufferIterator, _super);
14958 function ZipBufferIterator(destination, parent, observable) {
14959 _super.call(this, destination);
14960 this.parent = parent;
14961 this.observable = observable;
14962 this.stillUnsubscribed = true;
14964 this.isComplete = false;
14966 ZipBufferIterator.prototype[iterator_1.iterator] = function () {
14969 // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
14970 // this is legit because `next()` will never be called by a subscription in this case.
14971 ZipBufferIterator.prototype.next = function () {
14972 var buffer = this.buffer;
14973 if (buffer.length === 0 && this.isComplete) {
14974 return { value: null, done: true };
14977 return { value: buffer.shift(), done: false };
14980 ZipBufferIterator.prototype.hasValue = function () {
14981 return this.buffer.length > 0;
14983 ZipBufferIterator.prototype.hasCompleted = function () {
14984 return this.buffer.length === 0 && this.isComplete;
14986 ZipBufferIterator.prototype.notifyComplete = function () {
14987 if (this.buffer.length > 0) {
14988 this.isComplete = true;
14989 this.parent.notifyInactive();
14992 this.destination.complete();
14995 ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14996 this.buffer.push(innerValue);
14997 this.parent.checkIterators();
14999 ZipBufferIterator.prototype.subscribe = function (value, index) {
15000 return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
15002 return ZipBufferIterator;
15003 }(OuterSubscriber_1.OuterSubscriber));
15005 },{"../OuterSubscriber":31,"../Subscriber":36,"../observable/ArrayObservable":90,"../symbol/iterator":205,"../util/isArray":217,"../util/subscribeToResult":228}],198:[function(require,module,exports){
15007 var __extends = (this && this.__extends) || function (d, b) {
15008 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15009 function __() { this.constructor = d; }
15010 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15012 var Subscription_1 = require('../Subscription');
15014 * A unit of work to be executed in a {@link Scheduler}. An action is typically
15015 * created from within a Scheduler and an RxJS user does not need to concern
15016 * themselves about creating and manipulating an Action.
15019 * class Action<T> extends Subscription {
15020 * new (scheduler: Scheduler, work: (state?: T) => void);
15021 * schedule(state?: T, delay: number = 0): Subscription;
15027 var Action = (function (_super) {
15028 __extends(Action, _super);
15029 function Action(scheduler, work) {
15033 * Schedules this action on its parent Scheduler for execution. May be passed
15034 * some context object, `state`. May happen at some point in the future,
15035 * according to the `delay` parameter, if specified.
15036 * @param {T} [state] Some contextual data that the `work` function uses when
15037 * called by the Scheduler.
15038 * @param {number} [delay] Time to wait before executing the work, where the
15039 * time unit is implicit and defined by the Scheduler.
15042 Action.prototype.schedule = function (state, delay) {
15043 if (delay === void 0) { delay = 0; }
15047 }(Subscription_1.Subscription));
15048 exports.Action = Action;
15050 },{"../Subscription":37}],199:[function(require,module,exports){
15052 var __extends = (this && this.__extends) || function (d, b) {
15053 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15054 function __() { this.constructor = d; }
15055 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15057 var root_1 = require('../util/root');
15058 var Action_1 = require('./Action');
15060 * We need this JSDoc comment for affecting ESDoc.
15062 * @extends {Ignored}
15064 var AsyncAction = (function (_super) {
15065 __extends(AsyncAction, _super);
15066 function AsyncAction(scheduler, work) {
15067 _super.call(this, scheduler, work);
15068 this.scheduler = scheduler;
15070 this.pending = false;
15072 AsyncAction.prototype.schedule = function (state, delay) {
15073 if (delay === void 0) { delay = 0; }
15077 // Always replace the current state with the new state.
15078 this.state = state;
15079 // Set the pending flag indicating that this action has been scheduled, or
15080 // has recursively rescheduled itself.
15081 this.pending = true;
15083 var scheduler = this.scheduler;
15085 // Important implementation note:
15087 // Actions only execute once by default, unless rescheduled from within the
15088 // scheduled callback. This allows us to implement single and repeat
15089 // actions via the same code path, without adding API surface area, as well
15090 // as mimic traditional recursion but across asynchronous boundaries.
15092 // However, JS runtimes and timers distinguish between intervals achieved by
15093 // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
15094 // serial `setTimeout` calls can be individually delayed, which delays
15095 // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
15096 // guarantee the interval callback will be invoked more precisely to the
15097 // interval period, regardless of load.
15099 // Therefore, we use `setInterval` to schedule single and repeat actions.
15100 // If the action reschedules itself with the same delay, the interval is not
15101 // canceled. If the action doesn't reschedule, or reschedules with a
15102 // different delay, the interval will be canceled after scheduled callback
15106 this.id = this.recycleAsyncId(scheduler, id, delay);
15108 this.delay = delay;
15109 // If this action has already an async Id, don't request a new one.
15110 this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
15113 AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
15114 if (delay === void 0) { delay = 0; }
15115 return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
15117 AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
15118 if (delay === void 0) { delay = 0; }
15119 // If this action is rescheduled with the same delay time, don't clear the interval id.
15120 if (delay !== null && this.delay === delay && this.pending === false) {
15123 // Otherwise, if the action's delay time is different from the current delay,
15124 // or the action has been rescheduled before it's executed, clear the interval id
15125 return root_1.root.clearInterval(id) && undefined || undefined;
15128 * Immediately executes this action and the `work` it contains.
15131 AsyncAction.prototype.execute = function (state, delay) {
15133 return new Error('executing a cancelled action');
15135 this.pending = false;
15136 var error = this._execute(state, delay);
15140 else if (this.pending === false && this.id != null) {
15141 // Dequeue if the action didn't reschedule itself. Don't call
15142 // unsubscribe(), because the action could reschedule later.
15145 // scheduler.schedule(function doWork(counter) {
15146 // /* ... I'm a busy worker bee ... */
15147 // var originalAction = this;
15148 // /* wait 100ms before rescheduling the action */
15149 // setTimeout(function () {
15150 // originalAction.schedule(counter + 1);
15154 this.id = this.recycleAsyncId(this.scheduler, this.id, null);
15157 AsyncAction.prototype._execute = function (state, delay) {
15158 var errored = false;
15159 var errorValue = undefined;
15165 errorValue = !!e && e || new Error(e);
15168 this.unsubscribe();
15172 AsyncAction.prototype._unsubscribe = function () {
15174 var scheduler = this.scheduler;
15175 var actions = scheduler.actions;
15176 var index = actions.indexOf(this);
15179 this.pending = false;
15180 this.scheduler = null;
15181 if (index !== -1) {
15182 actions.splice(index, 1);
15185 this.id = this.recycleAsyncId(scheduler, id, null);
15189 return AsyncAction;
15190 }(Action_1.Action));
15191 exports.AsyncAction = AsyncAction;
15193 },{"../util/root":227,"./Action":198}],200:[function(require,module,exports){
15195 var __extends = (this && this.__extends) || function (d, b) {
15196 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15197 function __() { this.constructor = d; }
15198 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15200 var Scheduler_1 = require('../Scheduler');
15201 var AsyncScheduler = (function (_super) {
15202 __extends(AsyncScheduler, _super);
15203 function AsyncScheduler() {
15204 _super.apply(this, arguments);
15207 * A flag to indicate whether the Scheduler is currently executing a batch of
15211 this.active = false;
15213 * An internal ID used to track the latest asynchronous task such as those
15214 * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
15218 this.scheduled = undefined;
15220 AsyncScheduler.prototype.flush = function (action) {
15221 var actions = this.actions;
15223 actions.push(action);
15227 this.active = true;
15229 if (error = action.execute(action.state, action.delay)) {
15232 } while (action = actions.shift()); // exhaust the scheduler queue
15233 this.active = false;
15235 while (action = actions.shift()) {
15236 action.unsubscribe();
15241 return AsyncScheduler;
15242 }(Scheduler_1.Scheduler));
15243 exports.AsyncScheduler = AsyncScheduler;
15245 },{"../Scheduler":33}],201:[function(require,module,exports){
15247 var __extends = (this && this.__extends) || function (d, b) {
15248 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15249 function __() { this.constructor = d; }
15250 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15252 var AsyncAction_1 = require('./AsyncAction');
15254 * We need this JSDoc comment for affecting ESDoc.
15256 * @extends {Ignored}
15258 var QueueAction = (function (_super) {
15259 __extends(QueueAction, _super);
15260 function QueueAction(scheduler, work) {
15261 _super.call(this, scheduler, work);
15262 this.scheduler = scheduler;
15265 QueueAction.prototype.schedule = function (state, delay) {
15266 if (delay === void 0) { delay = 0; }
15268 return _super.prototype.schedule.call(this, state, delay);
15270 this.delay = delay;
15271 this.state = state;
15272 this.scheduler.flush(this);
15275 QueueAction.prototype.execute = function (state, delay) {
15276 return (delay > 0 || this.closed) ?
15277 _super.prototype.execute.call(this, state, delay) :
15278 this._execute(state, delay);
15280 QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
15281 if (delay === void 0) { delay = 0; }
15282 // If delay exists and is greater than 0, or if the delay is null (the
15283 // action wasn't rescheduled) but was originally scheduled as an async
15284 // action, then recycle as an async action.
15285 if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
15286 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
15288 // Otherwise flush the scheduler starting with this action.
15289 return scheduler.flush(this);
15291 return QueueAction;
15292 }(AsyncAction_1.AsyncAction));
15293 exports.QueueAction = QueueAction;
15295 },{"./AsyncAction":199}],202:[function(require,module,exports){
15297 var __extends = (this && this.__extends) || function (d, b) {
15298 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15299 function __() { this.constructor = d; }
15300 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15302 var AsyncScheduler_1 = require('./AsyncScheduler');
15303 var QueueScheduler = (function (_super) {
15304 __extends(QueueScheduler, _super);
15305 function QueueScheduler() {
15306 _super.apply(this, arguments);
15308 return QueueScheduler;
15309 }(AsyncScheduler_1.AsyncScheduler));
15310 exports.QueueScheduler = QueueScheduler;
15312 },{"./AsyncScheduler":200}],203:[function(require,module,exports){
15314 var AsyncAction_1 = require('./AsyncAction');
15315 var AsyncScheduler_1 = require('./AsyncScheduler');
15320 * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
15322 * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
15323 * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
15326 * If you just want to "defer" task, that is to perform it right after currently
15327 * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
15328 * better choice will be the {@link asap} scheduler.
15330 * @example <caption>Use async scheduler to delay task</caption>
15331 * const task = () => console.log('it works!');
15333 * Rx.Scheduler.async.schedule(task, 2000);
15335 * // After 2 seconds logs:
15339 * @example <caption>Use async scheduler to repeat task in intervals</caption>
15340 * function task(state) {
15341 * console.log(state);
15342 * this.schedule(state + 1, 1000); // `this` references currently executing Action,
15343 * // which we reschedule with new state and delay
15346 * Rx.Scheduler.async.schedule(task, 3000, 0);
15358 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
15360 },{"./AsyncAction":199,"./AsyncScheduler":200}],204:[function(require,module,exports){
15362 var QueueAction_1 = require('./QueueAction');
15363 var QueueScheduler_1 = require('./QueueScheduler');
15368 * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
15370 * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
15372 * When used without delay, it schedules given task synchronously - executes it right when
15373 * it is scheduled. However when called recursively, that is when inside the scheduled task,
15374 * another task is scheduled with queue scheduler, instead of executing immediately as well,
15375 * that task will be put on a queue and wait for current one to finish.
15377 * This means that when you execute task with `queue` scheduler, you are sure it will end
15378 * before any other task scheduled with that scheduler will start.
15380 * @examples <caption>Schedule recursively first, then do something</caption>
15382 * Rx.Scheduler.queue.schedule(() => {
15383 * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
15385 * console.log('first');
15393 * @example <caption>Reschedule itself recursively</caption>
15395 * Rx.Scheduler.queue.schedule(function(state) {
15396 * if (state !== 0) {
15397 * console.log('before', state);
15398 * this.schedule(state - 1); // `this` references currently executing Action,
15399 * // which we reschedule with new state
15400 * console.log('after', state);
15404 * // In scheduler that runs recursively, you would expect:
15412 * // But with queue it logs:
15425 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
15427 },{"./QueueAction":201,"./QueueScheduler":202}],205:[function(require,module,exports){
15429 var root_1 = require('../util/root');
15430 function symbolIteratorPonyfill(root) {
15431 var Symbol = root.Symbol;
15432 if (typeof Symbol === 'function') {
15433 if (!Symbol.iterator) {
15434 Symbol.iterator = Symbol('iterator polyfill');
15436 return Symbol.iterator;
15439 // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
15440 var Set_1 = root.Set;
15441 if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
15442 return '@@iterator';
15444 var Map_1 = root.Map;
15445 // required for compatability with es6-shim
15447 var keys = Object.getOwnPropertyNames(Map_1.prototype);
15448 for (var i = 0; i < keys.length; ++i) {
15450 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
15451 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
15456 return '@@iterator';
15459 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
15460 exports.iterator = symbolIteratorPonyfill(root_1.root);
15462 * @deprecated use iterator instead
15464 exports.$$iterator = exports.iterator;
15466 },{"../util/root":227}],206:[function(require,module,exports){
15468 var root_1 = require('../util/root');
15469 function getSymbolObservable(context) {
15471 var Symbol = context.Symbol;
15472 if (typeof Symbol === 'function') {
15473 if (Symbol.observable) {
15474 $$observable = Symbol.observable;
15477 $$observable = Symbol('observable');
15478 Symbol.observable = $$observable;
15482 $$observable = '@@observable';
15484 return $$observable;
15486 exports.getSymbolObservable = getSymbolObservable;
15487 exports.observable = getSymbolObservable(root_1.root);
15489 * @deprecated use observable instead
15491 exports.$$observable = exports.observable;
15493 },{"../util/root":227}],207:[function(require,module,exports){
15495 var root_1 = require('../util/root');
15496 var Symbol = root_1.root.Symbol;
15497 exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
15498 Symbol.for('rxSubscriber') : '@@rxSubscriber';
15500 * @deprecated use rxSubscriber instead
15502 exports.$$rxSubscriber = exports.rxSubscriber;
15504 },{"../util/root":227}],208:[function(require,module,exports){
15506 var root_1 = require('./root');
15507 var RequestAnimationFrameDefinition = (function () {
15508 function RequestAnimationFrameDefinition(root) {
15509 if (root.requestAnimationFrame) {
15510 this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
15511 this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
15513 else if (root.mozRequestAnimationFrame) {
15514 this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
15515 this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
15517 else if (root.webkitRequestAnimationFrame) {
15518 this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
15519 this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
15521 else if (root.msRequestAnimationFrame) {
15522 this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
15523 this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
15525 else if (root.oRequestAnimationFrame) {
15526 this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
15527 this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
15530 this.cancelAnimationFrame = root.clearTimeout.bind(root);
15531 this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
15534 return RequestAnimationFrameDefinition;
15536 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
15537 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
15539 },{"./root":227}],209:[function(require,module,exports){
15541 var __extends = (this && this.__extends) || function (d, b) {
15542 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15543 function __() { this.constructor = d; }
15544 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15547 * An error thrown when an element was queried at a certain index of an
15548 * Observable, but no such index or position exists in that sequence.
15550 * @see {@link elementAt}
15551 * @see {@link take}
15552 * @see {@link takeLast}
15554 * @class ArgumentOutOfRangeError
15556 var ArgumentOutOfRangeError = (function (_super) {
15557 __extends(ArgumentOutOfRangeError, _super);
15558 function ArgumentOutOfRangeError() {
15559 var err = _super.call(this, 'argument out of range');
15560 this.name = err.name = 'ArgumentOutOfRangeError';
15561 this.stack = err.stack;
15562 this.message = err.message;
15564 return ArgumentOutOfRangeError;
15566 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
15568 },{}],210:[function(require,module,exports){
15570 var __extends = (this && this.__extends) || function (d, b) {
15571 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15572 function __() { this.constructor = d; }
15573 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15576 * An error thrown when an Observable or a sequence was queried but has no
15579 * @see {@link first}
15580 * @see {@link last}
15581 * @see {@link single}
15583 * @class EmptyError
15585 var EmptyError = (function (_super) {
15586 __extends(EmptyError, _super);
15587 function EmptyError() {
15588 var err = _super.call(this, 'no elements in sequence');
15589 this.name = err.name = 'EmptyError';
15590 this.stack = err.stack;
15591 this.message = err.message;
15595 exports.EmptyError = EmptyError;
15597 },{}],211:[function(require,module,exports){
15599 var __extends = (this && this.__extends) || function (d, b) {
15600 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15601 function __() { this.constructor = d; }
15602 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15605 * An error thrown when an action is invalid because the object has been
15608 * @see {@link Subject}
15609 * @see {@link BehaviorSubject}
15611 * @class ObjectUnsubscribedError
15613 var ObjectUnsubscribedError = (function (_super) {
15614 __extends(ObjectUnsubscribedError, _super);
15615 function ObjectUnsubscribedError() {
15616 var err = _super.call(this, 'object unsubscribed');
15617 this.name = err.name = 'ObjectUnsubscribedError';
15618 this.stack = err.stack;
15619 this.message = err.message;
15621 return ObjectUnsubscribedError;
15623 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
15625 },{}],212:[function(require,module,exports){
15627 var root_1 = require('./root');
15628 function minimalSetImpl() {
15629 // THIS IS NOT a full impl of Set, this is just the minimum
15630 // bits of functionality we need for this library.
15631 return (function () {
15632 function MinimalSet() {
15635 MinimalSet.prototype.add = function (value) {
15636 if (!this.has(value)) {
15637 this._values.push(value);
15640 MinimalSet.prototype.has = function (value) {
15641 return this._values.indexOf(value) !== -1;
15643 Object.defineProperty(MinimalSet.prototype, "size", {
15645 return this._values.length;
15650 MinimalSet.prototype.clear = function () {
15651 this._values.length = 0;
15656 exports.minimalSetImpl = minimalSetImpl;
15657 exports.Set = root_1.root.Set || minimalSetImpl();
15659 },{"./root":227}],213:[function(require,module,exports){
15661 var __extends = (this && this.__extends) || function (d, b) {
15662 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15663 function __() { this.constructor = d; }
15664 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15667 * An error thrown when duetime elapses.
15669 * @see {@link timeout}
15671 * @class TimeoutError
15673 var TimeoutError = (function (_super) {
15674 __extends(TimeoutError, _super);
15675 function TimeoutError() {
15676 var err = _super.call(this, 'Timeout has occurred');
15677 this.name = err.name = 'TimeoutError';
15678 this.stack = err.stack;
15679 this.message = err.message;
15681 return TimeoutError;
15683 exports.TimeoutError = TimeoutError;
15685 },{}],214:[function(require,module,exports){
15687 var __extends = (this && this.__extends) || function (d, b) {
15688 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15689 function __() { this.constructor = d; }
15690 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15693 * An error thrown when one or more errors have occurred during the
15694 * `unsubscribe` of a {@link Subscription}.
15696 var UnsubscriptionError = (function (_super) {
15697 __extends(UnsubscriptionError, _super);
15698 function UnsubscriptionError(errors) {
15700 this.errors = errors;
15701 var err = Error.call(this, errors ?
15702 errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : '');
15703 this.name = err.name = 'UnsubscriptionError';
15704 this.stack = err.stack;
15705 this.message = err.message;
15707 return UnsubscriptionError;
15709 exports.UnsubscriptionError = UnsubscriptionError;
15711 },{}],215:[function(require,module,exports){
15713 // typeof any so that it we don't have to cast when comparing a result to the error object
15714 exports.errorObject = { e: {} };
15716 },{}],216:[function(require,module,exports){
15718 function identity(x) {
15721 exports.identity = identity;
15723 },{}],217:[function(require,module,exports){
15725 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
15727 },{}],218:[function(require,module,exports){
15729 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
15731 },{}],219:[function(require,module,exports){
15733 function isDate(value) {
15734 return value instanceof Date && !isNaN(+value);
15736 exports.isDate = isDate;
15738 },{}],220:[function(require,module,exports){
15740 function isFunction(x) {
15741 return typeof x === 'function';
15743 exports.isFunction = isFunction;
15745 },{}],221:[function(require,module,exports){
15747 var isArray_1 = require('../util/isArray');
15748 function isNumeric(val) {
15749 // parseFloat NaNs numeric-cast false positives (null|true|false|"")
15750 // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
15751 // subtraction forces infinities to NaN
15752 // adding 1 corrects loss of precision from parseFloat (#15100)
15753 return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
15755 exports.isNumeric = isNumeric;
15758 },{"../util/isArray":217}],222:[function(require,module,exports){
15760 function isObject(x) {
15761 return x != null && typeof x === 'object';
15763 exports.isObject = isObject;
15765 },{}],223:[function(require,module,exports){
15767 function isPromise(value) {
15768 return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
15770 exports.isPromise = isPromise;
15772 },{}],224:[function(require,module,exports){
15774 function isScheduler(value) {
15775 return value && typeof value.schedule === 'function';
15777 exports.isScheduler = isScheduler;
15779 },{}],225:[function(require,module,exports){
15781 /* tslint:disable:no-empty */
15782 function noop() { }
15783 exports.noop = noop;
15785 },{}],226:[function(require,module,exports){
15787 var noop_1 = require('./noop');
15788 /* tslint:enable:max-line-length */
15791 for (var _i = 0; _i < arguments.length; _i++) {
15792 fns[_i - 0] = arguments[_i];
15794 return pipeFromArray(fns);
15796 exports.pipe = pipe;
15798 function pipeFromArray(fns) {
15800 return noop_1.noop;
15802 if (fns.length === 1) {
15805 return function piped(input) {
15806 return fns.reduce(function (prev, fn) { return fn(prev); }, input);
15809 exports.pipeFromArray = pipeFromArray;
15811 },{"./noop":225}],227:[function(require,module,exports){
15812 (function (global){
15814 // CommonJS / Node have global context exposed as "global" variable.
15815 // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
15816 // the global "global" var for now.
15817 var __window = typeof window !== 'undefined' && window;
15818 var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
15819 self instanceof WorkerGlobalScope && self;
15820 var __global = typeof global !== 'undefined' && global;
15821 var _root = __window || __global || __self;
15822 exports.root = _root;
15823 // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
15824 // This is needed when used with angular/tsickle which inserts a goog.module statement.
15828 throw new Error('RxJS could not find any global context (window, self, global)');
15832 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15834 },{}],228:[function(require,module,exports){
15836 var root_1 = require('./root');
15837 var isArrayLike_1 = require('./isArrayLike');
15838 var isPromise_1 = require('./isPromise');
15839 var isObject_1 = require('./isObject');
15840 var Observable_1 = require('../Observable');
15841 var iterator_1 = require('../symbol/iterator');
15842 var InnerSubscriber_1 = require('../InnerSubscriber');
15843 var observable_1 = require('../symbol/observable');
15844 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
15845 var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
15846 if (destination.closed) {
15849 if (result instanceof Observable_1.Observable) {
15850 if (result._isScalar) {
15851 destination.next(result.value);
15852 destination.complete();
15856 destination.syncErrorThrowable = true;
15857 return result.subscribe(destination);
15860 else if (isArrayLike_1.isArrayLike(result)) {
15861 for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
15862 destination.next(result[i]);
15864 if (!destination.closed) {
15865 destination.complete();
15868 else if (isPromise_1.isPromise(result)) {
15869 result.then(function (value) {
15870 if (!destination.closed) {
15871 destination.next(value);
15872 destination.complete();
15874 }, function (err) { return destination.error(err); })
15875 .then(null, function (err) {
15876 // Escaping the Promise trap: globally throw unhandled errors
15877 root_1.root.setTimeout(function () { throw err; });
15879 return destination;
15881 else if (result && typeof result[iterator_1.iterator] === 'function') {
15882 var iterator = result[iterator_1.iterator]();
15884 var item = iterator.next();
15886 destination.complete();
15889 destination.next(item.value);
15890 if (destination.closed) {
15895 else if (result && typeof result[observable_1.observable] === 'function') {
15896 var obs = result[observable_1.observable]();
15897 if (typeof obs.subscribe !== 'function') {
15898 destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
15901 return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
15905 var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
15906 var msg = ("You provided " + value + " where a stream was expected.")
15907 + ' You can provide an Observable, Promise, Array, or Iterable.';
15908 destination.error(new TypeError(msg));
15912 exports.subscribeToResult = subscribeToResult;
15914 },{"../InnerSubscriber":27,"../Observable":29,"../symbol/iterator":205,"../symbol/observable":206,"./isArrayLike":218,"./isObject":222,"./isPromise":223,"./root":227}],229:[function(require,module,exports){
15916 var Subscriber_1 = require('../Subscriber');
15917 var rxSubscriber_1 = require('../symbol/rxSubscriber');
15918 var Observer_1 = require('../Observer');
15919 function toSubscriber(nextOrObserver, error, complete) {
15920 if (nextOrObserver) {
15921 if (nextOrObserver instanceof Subscriber_1.Subscriber) {
15922 return nextOrObserver;
15924 if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
15925 return nextOrObserver[rxSubscriber_1.rxSubscriber]();
15928 if (!nextOrObserver && !error && !complete) {
15929 return new Subscriber_1.Subscriber(Observer_1.empty);
15931 return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
15933 exports.toSubscriber = toSubscriber;
15935 },{"../Observer":30,"../Subscriber":36,"../symbol/rxSubscriber":207}],230:[function(require,module,exports){
15937 var errorObject_1 = require('./errorObject');
15938 var tryCatchTarget;
15939 function tryCatcher() {
15941 return tryCatchTarget.apply(this, arguments);
15944 errorObject_1.errorObject.e = e;
15945 return errorObject_1.errorObject;
15948 function tryCatch(fn) {
15949 tryCatchTarget = fn;
15952 exports.tryCatch = tryCatch;
15955 },{"./errorObject":215}],231:[function(require,module,exports){
15956 // threejs.org/license
15957 (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<arguments.length&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function Z(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}
15958 function p(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function ra(){this.elements=[1,0,0,0,1,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function ea(a,b,c,d,e,f,g,h,k,l){Object.defineProperty(this,"id",{value:kf++});this.uuid=R.generateUUID();this.name="";this.image=void 0!==a?a:ea.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ea.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=void 0!==d?d:1001;this.magFilter=
15959 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 C(0,0);this.repeat=new C(1,1);this.center=new C(0,0);this.rotation=0;this.matrixAutoUpdate=!0;this.matrix=new ra;this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==l?l:3E3;this.version=0;this.onUpdate=null}function da(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Hb(a,
15960 b,c){this.uuid=R.generateUUID();this.width=a;this.height=b;this.scissor=new da(0,0,a,b);this.scissorTest=!1;this.viewport=new da(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ea(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 Ib(a,b,c){Hb.call(this,
15961 a,b,c);this.activeMipMapLevel=this.activeCubeFace=0}function fb(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={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==l?l:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Ua(a,b,c,d,e,f,g,h,k,l){a=void 0!==a?a:[];ea.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,l);this.flipY=!1}function Jb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=we[e];void 0===f&&(f=new Float32Array(e),
15962 we[e]=f);if(0!==b)for(d.toArray(f,0),d=1,e=0;d!==b;++d)e+=c,a[d].toArray(f,e);return f}function xe(a,b){var c=ye[b];void 0===c&&(c=new Int32Array(b),ye[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function lf(a,b){a.uniform1f(this.addr,b)}function mf(a,b){a.uniform1i(this.addr,b)}function nf(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function of(a,b){void 0!==b.x?a.uniform3f(this.addr,b.x,b.y,b.z):void 0!==b.r?a.uniform3f(this.addr,b.r,b.g,b.b):a.uniform3fv(this.addr,
15963 b)}function pf(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function qf(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function rf(a,b){void 0===b.elements?a.uniformMatrix3fv(this.addr,!1,b):(ze.set(b.elements),a.uniformMatrix3fv(this.addr,!1,ze))}function sf(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(Ae.set(b.elements),a.uniformMatrix4fv(this.addr,!1,Ae))}function tf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||
15964 Be,d)}function uf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTextureCube(b||Ce,d)}function De(a,b){a.uniform2iv(this.addr,b)}function Ee(a,b){a.uniform3iv(this.addr,b)}function Fe(a,b){a.uniform4iv(this.addr,b)}function vf(a){switch(a){case 5126:return lf;case 35664:return nf;case 35665:return of;case 35666:return pf;case 35674:return qf;case 35675:return rf;case 35676:return sf;case 35678:case 36198:return tf;case 35680:return uf;case 5124:case 35670:return mf;case 35667:case 35671:return De;
15965 case 35668:case 35672:return Ee;case 35669:case 35673:return Fe}}function wf(a,b){a.uniform1fv(this.addr,b)}function xf(a,b){a.uniform1iv(this.addr,b)}function yf(a,b){a.uniform2fv(this.addr,Jb(b,this.size,2))}function zf(a,b){a.uniform3fv(this.addr,Jb(b,this.size,3))}function Af(a,b){a.uniform4fv(this.addr,Jb(b,this.size,4))}function Bf(a,b){a.uniformMatrix2fv(this.addr,!1,Jb(b,this.size,4))}function Cf(a,b){a.uniformMatrix3fv(this.addr,!1,Jb(b,this.size,9))}function Df(a,b){a.uniformMatrix4fv(this.addr,
15966 !1,Jb(b,this.size,16))}function Ef(a,b,c){var d=b.length,e=xe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||Be,e[a])}function Ff(a,b,c){var d=b.length,e=xe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||Ce,e[a])}function Gf(a){switch(a){case 5126:return wf;case 35664:return yf;case 35665:return zf;case 35666:return Af;case 35674:return Bf;case 35675:return Cf;case 35676:return Df;case 35678:return Ef;case 35680:return Ff;case 5124:case 35670:return xf;
15967 case 35667:case 35671:return De;case 35668:case 35672:return Ee;case 35669:case 35673:return Fe}}function Hf(a,b,c){this.id=a;this.addr=c;this.setValue=vf(b.type)}function If(a,b,c){this.id=a;this.addr=c;this.size=b.size;this.setValue=Gf(b.type)}function Ge(a){this.id=a;this.seq=[];this.map={}}function gb(a,b,c){this.seq=[];this.map={};this.renderer=c;c=a.getProgramParameter(b,a.ACTIVE_UNIFORMS);for(var d=0;d<c;++d){var e=a.getActiveUniform(b,d),f=a.getUniformLocation(b,e.name),g=this,h=e.name,k=
15968 h.length;for(Od.lastIndex=0;;){var l=Od.exec(h),q=Od.lastIndex,n=l[1],t=l[3];"]"===l[2]&&(n|=0);if(void 0===t||"["===t&&q+2===k){h=g;e=void 0===t?new Hf(n,e,f):new If(n,e,f);h.seq.push(e);h.map[e.id]=e;break}else t=g.map[n],void 0===t&&(t=new Ge(n),n=g,g=t,n.seq.push(g),n.map[g.id]=g),g=t}}}function H(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function kd(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function Jf(a,b,c,
15969 d,e){var f,g,h,k,l,q,n,t,r,m,v,w,x,z,I,B;this.render=function(a,u,za,la){if(0!==a.length){u=new p;var J=la.w/la.z,ta=.5*la.z,Va=.5*la.w,L=16/la.w,Y=new C(L*J,L),ua=new p(1,1,0),M=new C(1,1),V=new kd;V.min.set(la.x,la.y);V.max.set(la.x+(la.z-16),la.y+(la.w-16));if(void 0===z){var L=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),y=new Uint16Array([0,1,2,0,2,3]);v=b.createBuffer();w=b.createBuffer();b.bindBuffer(b.ARRAY_BUFFER,v);b.bufferData(b.ARRAY_BUFFER,L,b.STATIC_DRAW);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,
15970 w);b.bufferData(b.ELEMENT_ARRAY_BUFFER,y,b.STATIC_DRAW);I=b.createTexture();B=b.createTexture();c.bindTexture(b.TEXTURE_2D,I);b.texImage2D(b.TEXTURE_2D,0,b.RGB,16,16,0,b.RGB,b.UNSIGNED_BYTE,null);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST);c.bindTexture(b.TEXTURE_2D,B);b.texImage2D(b.TEXTURE_2D,0,
15971 b.RGBA,16,16,0,b.RGBA,b.UNSIGNED_BYTE,null);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST);var L=x={vertexShader:"uniform lowp int renderType;\nuniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform sampler2D occlusionMap;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\n\tvUV = uv;\n\tvec2 pos = position;\n\tif ( renderType == 2 ) {\n\t\tvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\n\t\tvVisibility = visibility.r / 9.0;\n\t\tvVisibility *= 1.0 - visibility.g / 9.0;\n\t\tvVisibility *= visibility.b / 9.0;\n\t\tvVisibility *= 1.0 - visibility.a / 9.0;\n\t\tpos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\n\t\tpos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n\t}\n\tgl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
15972 fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\n\tif ( renderType == 0 ) {\n\t\tgl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n\t} else if ( renderType == 1 ) {\n\t\tgl_FragColor = texture2D( map, vUV );\n\t} else {\n\t\tvec4 texture = texture2D( map, vUV );\n\t\ttexture.a *= opacity * vVisibility;\n\t\tgl_FragColor = texture;\n\t\tgl_FragColor.rgb *= color;\n\t}\n}"},y=b.createProgram(),
15973 A=b.createShader(b.FRAGMENT_SHADER),aa=b.createShader(b.VERTEX_SHADER),D="precision "+e.precision+" float;\n";b.shaderSource(A,D+L.fragmentShader);b.shaderSource(aa,D+L.vertexShader);b.compileShader(A);b.compileShader(aa);b.attachShader(y,A);b.attachShader(y,aa);b.linkProgram(y);z=y;r=b.getAttribLocation(z,"position");m=b.getAttribLocation(z,"uv");f=b.getUniformLocation(z,"renderType");g=b.getUniformLocation(z,"map");h=b.getUniformLocation(z,"occlusionMap");k=b.getUniformLocation(z,"opacity");l=b.getUniformLocation(z,
15974 "color");q=b.getUniformLocation(z,"scale");n=b.getUniformLocation(z,"rotation");t=b.getUniformLocation(z,"screenPosition")}c.useProgram(z);c.initAttributes();c.enableAttribute(r);c.enableAttribute(m);c.disableUnusedAttributes();b.uniform1i(h,0);b.uniform1i(g,1);b.bindBuffer(b.ARRAY_BUFFER,v);b.vertexAttribPointer(r,2,b.FLOAT,!1,16,0);b.vertexAttribPointer(m,2,b.FLOAT,!1,16,8);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,w);c.disable(b.CULL_FACE);c.buffers.depth.setMask(!1);y=0;for(A=a.length;y<A;y++)if(L=
15975 16/la.w,Y.set(L*J,L),aa=a[y],u.set(aa.matrixWorld.elements[12],aa.matrixWorld.elements[13],aa.matrixWorld.elements[14]),u.applyMatrix4(za.matrixWorldInverse),u.applyMatrix4(za.projectionMatrix),ua.copy(u),M.x=la.x+ua.x*ta+ta-8,M.y=la.y+ua.y*Va+Va-8,!0===V.containsPoint(M)){c.activeTexture(b.TEXTURE0);c.bindTexture(b.TEXTURE_2D,null);c.activeTexture(b.TEXTURE1);c.bindTexture(b.TEXTURE_2D,I);b.copyTexImage2D(b.TEXTURE_2D,0,b.RGB,M.x,M.y,16,16,0);b.uniform1i(f,0);b.uniform2f(q,Y.x,Y.y);b.uniform3f(t,
15976 ua.x,ua.y,ua.z);c.disable(b.BLEND);c.enable(b.DEPTH_TEST);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);c.activeTexture(b.TEXTURE0);c.bindTexture(b.TEXTURE_2D,B);b.copyTexImage2D(b.TEXTURE_2D,0,b.RGBA,M.x,M.y,16,16,0);b.uniform1i(f,1);c.disable(b.DEPTH_TEST);c.activeTexture(b.TEXTURE1);c.bindTexture(b.TEXTURE_2D,I);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);aa.positionScreen.copy(ua);aa.customUpdateCallback?aa.customUpdateCallback(aa):aa.updateLensFlares();b.uniform1i(f,2);c.enable(b.BLEND);
15977 for(var D=0,H=aa.lensFlares.length;D<H;D++){var E=aa.lensFlares[D];.001<E.opacity&&.001<E.scale&&(ua.x=E.x,ua.y=E.y,ua.z=E.z,L=E.size*E.scale/la.w,Y.x=L*J,Y.y=L,b.uniform3f(t,ua.x,ua.y,ua.z),b.uniform2f(q,Y.x,Y.y),b.uniform1f(n,E.rotation),b.uniform1f(k,E.opacity),b.uniform3f(l,E.color.r,E.color.g,E.color.b),c.setBlending(E.blending,E.blendEquation,E.blendSrc,E.blendDst),d.setTexture2D(E.texture,1),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0))}}c.enable(b.CULL_FACE);c.enable(b.DEPTH_TEST);c.buffers.depth.setMask(!0);
15978 c.reset()}}}function tc(a,b,c,d,e,f,g,h,k){ea.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Kf(a,b,c,d,e){var f,g,h,k,l,q,n,t,r,m,v,w,x,z,I,B,J;function ta(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var za,la,ha,He,Va=new p,L=new Z,C=new p;this.render=function(u,p,V){if(0!==u.length){if(void 0===ha){var M=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),y=new Uint16Array([0,1,2,0,2,3]);za=b.createBuffer();la=b.createBuffer();
15979 b.bindBuffer(b.ARRAY_BUFFER,za);b.bufferData(b.ARRAY_BUFFER,M,b.STATIC_DRAW);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,la);b.bufferData(b.ELEMENT_ARRAY_BUFFER,y,b.STATIC_DRAW);M=b.createProgram();y=b.createShader(b.VERTEX_SHADER);var Y=b.createShader(b.FRAGMENT_SHADER);b.shaderSource(y,["precision "+e.precision+" float;","#define SHADER_NAME SpriteMaterial\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform float rotation;\nuniform vec2 scale;\nuniform vec2 uvOffset;\nuniform vec2 uvScale;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float fogDepth;\nvoid main() {\n\tvUV = uvOffset + uv * uvScale;\n\tvec2 alignedPosition = position * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tvec4 mvPosition;\n\tmvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\tfogDepth = - mvPosition.z;\n}"].join("\n"));
15980 b.shaderSource(Y,["precision "+e.precision+" float;","#define SHADER_NAME SpriteMaterial\nuniform vec3 color;\nuniform sampler2D map;\nuniform float opacity;\nuniform int fogType;\nuniform vec3 fogColor;\nuniform float fogDensity;\nuniform float fogNear;\nuniform float fogFar;\nuniform float alphaTest;\nvarying vec2 vUV;\nvarying float fogDepth;\nvoid main() {\n\tvec4 texture = texture2D( map, vUV );\n\tgl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\n\tif ( gl_FragColor.a < alphaTest ) discard;\n\tif ( fogType > 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"));
15981 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");
15982 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);
15983 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),
15984 b.uniform1i(m,2),y=M=2)):(b.uniform1i(m,0),y=M=0);for(var A=0,ua=u.length;A<ua;A++)Y=u[A],Y.modelViewMatrix.multiplyMatrices(V.matrixWorldInverse,Y.matrixWorld),Y.z=-Y.modelViewMatrix.elements[14];u.sort(ta);for(var E=[],A=0,ua=u.length;A<ua;A++){Y=u[A];var G=Y.material;if(!1!==G.visible){Y.onBeforeRender(a,p,V,void 0,G,void 0);b.uniform1f(I,G.alphaTest);b.uniformMatrix4fv(t,!1,Y.modelViewMatrix.elements);Y.matrixWorld.decompose(Va,L,C);E[0]=C.x;E[1]=C.y;var D=0;p.fog&&G.fog&&(D=y);M!==D&&(b.uniform1i(m,
15985 D),M=D);null!==G.map?(b.uniform2f(f,G.map.offset.x,G.map.offset.y),b.uniform2f(g,G.map.repeat.x,G.map.repeat.y)):(b.uniform2f(f,0,0),b.uniform2f(g,1,1));b.uniform1f(n,G.opacity);b.uniform3f(l,G.color.r,G.color.g,G.color.b);b.uniform1f(h,G.rotation);b.uniform2fv(k,E);c.setBlending(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.premultipliedAlpha);c.buffers.depth.setTest(G.depthTest);c.buffers.depth.setMask(G.depthWrite);c.buffers.color.setMask(G.colorWrite);
15986 d.setTexture2D(G.map||He,0);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);Y.onAfterRender(a,p,V,void 0,G,void 0)}}c.enable(b.CULL_FACE);c.reset()}}}function Q(){Object.defineProperty(this,"id",{value:Lf++});this.uuid=R.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.flatShading=!1;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=
15987 null;this.depthFunc=3;this.depthWrite=this.depthTest=!0;this.clippingPlanes=null;this.clipShadows=this.clipIntersection=!1;this.colorWrite=!0;this.precision=null;this.polygonOffset=!1;this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.dithering=!1;this.alphaTest=0;this.premultipliedAlpha=!1;this.overdraw=0;this.visible=!0;this.userData={};this.needsUpdate=!0}function Wa(a){Q.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=this.skinning=!1;this.displacementMap=
15988 this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function Xa(a){Q.call(this);this.type="MeshDistanceMaterial";this.referencePosition=new p;this.nearDistance=1;this.farDistance=1E3;this.morphTargets=this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.lights=this.fog=!1;this.setValues(a)}function Oa(a,b){this.min=void 0!==
15989 a?a:new p(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new p(-Infinity,-Infinity,-Infinity)}function Da(a,b){this.center=void 0!==a?a:new p;this.radius=void 0!==b?b:0}function Aa(a,b){this.normal=void 0!==a?a:new p(1,0,0);this.constant=void 0!==b?b:0}function ld(a,b,c,d,e,f){this.planes=[void 0!==a?a:new Aa,void 0!==b?b:new Aa,void 0!==c?c:new Aa,void 0!==d?d:new Aa,void 0!==e?e:new Aa,void 0!==f?f:new Aa]}function Ie(a,b,c){function d(b,c,d,e,f,g){var h=b.geometry;var k=n;var l=b.customDepthMaterial;
15990 d&&(k=t,l=b.customDistanceMaterial);l?k=l:(l=!1,c.morphTargets&&(h&&h.isBufferGeometry?l=h.morphAttributes&&h.morphAttributes.position&&0<h.morphAttributes.position.length:h&&h.isGeometry&&(l=h.morphTargets&&0<h.morphTargets.length)),b.isSkinnedMesh&&!1===c.skinning&&console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",b),b=b.isSkinnedMesh&&c.skinning,h=0,l&&(h|=1),b&&(h|=2),k=k[h]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(h=
15991 k.uuid,l=c.uuid,b=r[h],void 0===b&&(b={},r[h]=b),h=b[l],void 0===h&&(h=k.clone(),b[l]=h),k=h);k.visible=c.visible;k.wireframe=c.wireframe;l=c.side;B.renderSingleSided&&2==l&&(l=0);B.renderReverseSided&&(0===l?l=1:1===l&&(l=0));k.side=l;k.clipShadows=c.clipShadows;k.clippingPlanes=c.clippingPlanes;k.clipIntersection=c.clipIntersection;k.wireframeLinewidth=c.wireframeLinewidth;k.linewidth=c.linewidth;d&&k.isMeshDistanceMaterial&&(k.referencePosition.copy(e),k.nearDistance=f,k.farDistance=g);return k}
15992 function e(c,g,h,k){var l;if(!1!==c.visible){if(c.layers.test(g.layers)&&(c.isMesh||c.isLine||c.isPoints)&&c.castShadow&&(!c.frustumCulled||f.intersectsObject(c))){c.modelViewMatrix.multiplyMatrices(h.matrixWorldInverse,c.matrixWorld);var n=b.update(c),t=c.material;if(Array.isArray(t))for(var r=n.groups,m=0,z=r.length;m<z;m++){var u=r[m];(l=t[u.materialIndex])&&l.visible&&(l=d(c,l,k,q,h.near,h.far),a.renderBufferDirect(h,null,n,l,c,u))}else t.visible&&(l=d(c,t,k,q,h.near,h.far),a.renderBufferDirect(h,
15993 null,n,l,c,null))}c=c.children;n=0;for(t=c.length;n<t;n++)e(c[n],g,h,k)}}var f=new ld,g=new K,h=new C,k=new C(c,c),l=new p,q=new p,n=Array(4),t=Array(4),r={},m=[new p(1,0,0),new p(-1,0,0),new p(0,0,1),new p(0,0,-1),new p(0,1,0),new p(0,-1,0)],v=[new p(0,1,0),new p(0,1,0),new p(0,1,0),new p(0,1,0),new p(0,0,1),new p(0,0,-1)],w=[new da,new da,new da,new da,new da,new da];for(c=0;4!==c;++c){var x=0!==(c&1),z=0!==(c&2),I=new Wa({depthPacking:3201,morphTargets:x,skinning:z});n[c]=I;x=new Xa({morphTargets:x,
15994 skinning:z});t[c]=x}var B=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,c,d){if(!1!==B.enabled&&(!1!==B.autoUpdate||!1!==B.needsUpdate)&&0!==b.length){var n=a.state;n.disable(a.context.BLEND);n.buffers.color.setClear(1,1,1,1);n.buffers.depth.setTest(!0);n.setScissorTest(!1);for(var t,r=0,z=b.length;r<z;r++){var u=b[r];t=u.shadow;var I=u&&u.isPointLight;if(void 0===t)console.warn("THREE.WebGLShadowMap:",
15995 u,"has no shadow.");else{var p=t.camera;h.copy(t.mapSize);h.min(k);if(I){var x=h.x,J=h.y;w[0].set(2*x,J,x,J);w[1].set(0,J,x,J);w[2].set(3*x,J,x,J);w[3].set(x,J,x,J);w[4].set(3*x,0,x,J);w[5].set(x,0,x,J);h.x*=4;h.y*=2}null===t.map&&(t.map=new Hb(h.x,h.y,{minFilter:1003,magFilter:1003,format:1023}),t.map.texture.name=u.name+".shadowMap",p.updateProjectionMatrix());t.isSpotLightShadow&&t.update(u);x=t.map;J=t.matrix;q.setFromMatrixPosition(u.matrixWorld);p.position.copy(q);I?(t=6,J.makeTranslation(-q.x,
15996 -q.y,-q.z)):(t=1,l.setFromMatrixPosition(u.target.matrixWorld),p.lookAt(l),p.updateMatrixWorld(),J.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),J.multiply(p.projectionMatrix),J.multiply(p.matrixWorldInverse));a.setRenderTarget(x);a.clear();for(u=0;u<t;u++)I&&(l.copy(p.position),l.add(m[u]),p.up.copy(v[u]),p.lookAt(l),p.updateMatrixWorld(),n.viewport(w[u])),g.multiplyMatrices(p.projectionMatrix,p.matrixWorldInverse),f.setFromMatrix(g),e(c,d,p,I)}}B.needsUpdate=!1}}}function Mf(a){var b={};return{get:function(a){a.isInterleavedBufferAttribute&&
15997 (a=a.data);return b[a.uuid]},remove:function(c){c.isInterleavedBufferAttribute&&(c=c.data);var d=b[c.uuid];d&&(a.deleteBuffer(d.buffer),delete b[c.uuid])},update:function(c,d){c.isInterleavedBufferAttribute&&(c=c.data);var e=b[c.uuid];if(void 0===e){var e=c.uuid,f=c.array,g=c.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,h=a.createBuffer();a.bindBuffer(d,h);a.bufferData(d,f,g);c.onUploadCallback();d=a.FLOAT;f instanceof Float32Array?d=a.FLOAT:f instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):
15998 f instanceof Uint16Array?d=a.UNSIGNED_SHORT:f instanceof Int16Array?d=a.SHORT:f instanceof Uint32Array?d=a.UNSIGNED_INT:f instanceof Int32Array?d=a.INT:f instanceof Int8Array?d=a.BYTE:f instanceof Uint8Array&&(d=a.UNSIGNED_BYTE);b[e]={buffer:h,type:d,bytesPerElement:f.BYTES_PER_ELEMENT,version:c.version}}else e.version<c.version&&(f=c,h=f.array,g=f.updateRange,a.bindBuffer(d,e.buffer),!1===f.dynamic?a.bufferData(d,h,a.STATIC_DRAW):-1===g.count?a.bufferSubData(d,0,h):0===g.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):
15999 (a.bufferSubData(d,g.offset*h.BYTES_PER_ELEMENT,h.subarray(g.offset,g.offset+g.count)),g.count=-1),e.version=c.version)}}}function Ya(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||Ya.DefaultOrder}function Pd(){this.mask=1}function A(){Object.defineProperty(this,"id",{value:Nf++});this.uuid=R.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=A.DefaultUp.clone();var a=new p,b=new Ya,c=new Z,d=new p(1,1,1);b.onChange(function(){c.setFromEuler(b,
16000 !1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,{position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new K},normalMatrix:{value:new ra}});this.matrix=new K;this.matrixWorld=new K;this.matrixAutoUpdate=A.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Pd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=
16001 0;this.userData={}}function La(){A.call(this);this.type="Camera";this.matrixWorldInverse=new K;this.projectionMatrix=new K}function Kb(a,b,c,d,e,f){La.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function Pa(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new p;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?
16002 e:new H;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function N(){Object.defineProperty(this,"id",{value:Of+=2});this.uuid=R.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=
16003 this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function P(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=R.generateUUID();this.name="";this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function uc(a,b,c){P.call(this,new Int8Array(a),b,c)}function vc(a,b,c){P.call(this,new Uint8Array(a),
16004 b,c)}function wc(a,b,c){P.call(this,new Uint8ClampedArray(a),b,c)}function xc(a,b,c){P.call(this,new Int16Array(a),b,c)}function hb(a,b,c){P.call(this,new Uint16Array(a),b,c)}function yc(a,b,c){P.call(this,new Int32Array(a),b,c)}function ib(a,b,c){P.call(this,new Uint32Array(a),b,c)}function y(a,b,c){P.call(this,new Float32Array(a),b,c)}function zc(a,b,c){P.call(this,new Float64Array(a),b,c)}function Je(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=
16005 [];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function Qd(a){if(0===a.length)return-Infinity;for(var b=a[0],c=1,d=a.length;c<d;++c)a[c]>b&&(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=
16006 {};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;y<B;y++){var A=y*u-w;for(J=0;J<g;J++)C[a]=
16007 (J*z-v)*d,C[b]=A*e,C[c]=I,l.push(C.x,C.y,C.z),C[a]=0,C[b]=0,C[c]=0<m?1:-1,q.push(C.x,C.y,C.z),n.push(J/ta),n.push(1-y/za),f+=1}for(y=0;y<za;y++)for(J=0;J<ta;J++)a=t+J+g*(y+1),b=t+(J+1)+g*(y+1),c=t+(J+1)+g*y,k.push(t+J+g*y,a,c),k.push(a,b,c),x+=6;h.addGroup(r,x,la);r+=x;t+=f}D.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;a=a||1;b=b||1;c=c||1;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=
16008 [],l=[],q=[],n=[],t=0,r=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x","z","y",1,-1,a,c,-b,d,f,3);g("x","y","z",1,-1,a,b,c,d,e,4);g("x","y","z",-1,-1,a,b,-c,d,e,5);this.setIndex(k);this.addAttribute("position",new y(l,3));this.addAttribute("normal",new y(q,3));this.addAttribute("uv",new y(n,2))}function Ac(a,b,c,d){N.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new kb(a,
16009 b,c,d));this.mergeVertices()}function kb(a,b,c,d){D.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};a=a||1;b=b||1;var e=a/2,f=b/2;c=Math.floor(c)||1;d=Math.floor(d)||1;var g=c+1,h=d+1,k=a/c,l=b/d,q=[],n=[],t=[],r=[];for(a=0;a<h;a++){var m=a*l-f;for(b=0;b<g;b++)n.push(b*k-e,-m,0),t.push(0,0,1),r.push(b/c),r.push(1-a/d)}for(a=0;a<d;a++)for(b=0;b<c;b++)e=b+g*(a+1),f=b+1+g*(a+1),h=b+1+g*a,q.push(b+g*a,e,h),q.push(e,f,h);this.setIndex(q);this.addAttribute("position",
16010 new y(n,3));this.addAttribute("normal",new y(t,3));this.addAttribute("uv",new y(r,2))}function va(a){Q.call(this);this.type="MeshBasicMaterial";this.color=new H(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=this.morphTargets=this.skinning=
16011 !1;this.setValues(a)}function oa(a){Q.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.clipping=this.lights=this.fog=!1;this.extensions={derivatives:!1,fragDepth:!1,
16012 drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function lb(a,b){this.origin=void 0!==a?a:new p;this.direction=void 0!==b?b:new p}function Mb(a,b){this.start=void 0!==a?a:new p;this.end=void 0!==b?b:new p}function Qa(a,b,c){this.a=void 0!==a?a:new p;this.b=void 0!==
16013 b?b:new p;this.c=void 0!==c?c:new p}function pa(a,b){A.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new va({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Qf(a,b,c,d){function e(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var f=new H(0),g=0,h,k,l;return{getClearColor:function(){return f},setClearColor:function(a,b){f.set(a);g=void 0!==b?b:1;e(f,g)},getClearAlpha:function(){return g},setClearAlpha:function(a){g=a;e(f,
16014 g)},render:function(b,d,t,r){d=d.background;null===d?e(f,g):d&&d.isColor&&(e(d,1),r=!0);(a.autoClear||r)&&a.clear(a.autoClearColor,a.autoClearDepth,a.autoClearStencil);d&&d.isCubeTexture?(void 0===l&&(l=new pa(new jb(1,1,1),new oa({uniforms:mb.cube.uniforms,vertexShader:mb.cube.vertexShader,fragmentShader:mb.cube.fragmentShader,side:1,depthTest:!0,depthWrite:!1,fog:!1})),l.geometry.removeAttribute("normal"),l.geometry.removeAttribute("uv"),l.onBeforeRender=function(a,b,c){this.matrixWorld.copyPosition(c.matrixWorld)},
16015 c.update(l.geometry)),l.material.uniforms.tCube.value=d,b.push(l,l.geometry,l.material,0,null)):d&&d.isTexture&&(void 0===h&&(h=new Kb(-1,1,1,-1,0,1),k=new pa(new kb(2,2),new va({depthTest:!1,depthWrite:!1,fog:!1})),c.update(k.geometry)),k.material.map=d,a.renderBufferDirect(h,null,k.geometry,k.material,k,null))}}}function Rf(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.program&&b.program&&a.program!==b.program?a.program.id-b.program.id:a.material.id!==b.material.id?a.material.id-
16016 b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Sf(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Tf(){var a=[],b=0,c=[],d=[];return{opaque:c,transparent:d,init:function(){b=0;c.length=0;d.length=0},push:function(e,f,g,h,k){var l=a[b];void 0===l?(l={id:e.id,object:e,geometry:f,material:g,program:g.program,renderOrder:e.renderOrder,z:h,group:k},a[b]=l):(l.id=e.id,l.object=e,l.geometry=f,l.material=g,l.program=g.program,l.renderOrder=e.renderOrder,
16017 l.z=h,l.group=k);(!0===g.transparent?d:c).push(l);b++},sort:function(){1<c.length&&c.sort(Rf);1<d.length&&d.sort(Sf)}}}function Uf(){var a={};return{get:function(b,c){b=b.id+","+c.id;c=a[b];void 0===c&&(c=new Tf,a[b]=c);return c},dispose:function(){a={}}}}function Vf(a,b){return Math.abs(b[1])-Math.abs(a[1])}function Wf(a){var b={},c=new Float32Array(8);return{update:function(d,e,f,g){var h=d.morphTargetInfluences,k=h.length;d=b[e.id];if(void 0===d){d=[];for(var l=0;l<k;l++)d[l]=[l,0];b[e.id]=d}var q=
16018 f.morphTargets&&e.morphAttributes.position;f=f.morphNormals&&e.morphAttributes.normal;for(l=0;l<k;l++){var n=d[l];0!==n[1]&&(q&&e.removeAttribute("morphTarget"+l),f&&e.removeAttribute("morphNormal"+l))}for(l=0;l<k;l++)n=d[l],n[0]=l,n[1]=h[l];d.sort(Vf);for(l=0;8>l;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=
16019 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+=
16020 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.");
16021 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",
16022 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],
16023 a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=c[f],e=0,g=d.length;e<g;e++)b.update(d[e],a.ARRAY_BUFFER)},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;d=[];var e=c.index;var g=c.attributes;if(null!==e){var q=e.array;for(var n=0,t=q.length;n<t;n+=3){var r=q[n+0];g=q[n+1];e=q[n+2];d.push(r,g,g,e,e,r)}}else for(q=g.position.array,n=0,t=q.length/3-1;n<t;n+=3)r=n+0,g=n+1,e=n+2,d.push(r,g,g,e,e,r);d=new (65535<Qd(d)?ib:hb)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=
16024 d}}}function $f(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];switch(b.type){case "DirectionalLight":var c={direction:new p,color:new H,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new p,direction:new p,color:new H,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "PointLight":c={position:new p,color:new H,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C,
16025 shadowCameraNear:1,shadowCameraFar:1E3};break;case "HemisphereLight":c={direction:new p,skyColor:new H,groundColor:new H};break;case "RectAreaLight":c={color:new H,position:new p,halfWidth:new p,halfHeight:new p}}return a[b.id]=c}}}function ag(){var a=new $f,b={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]},c=new p,d=new K,e=new K;return{setup:function(f,
16026 g,h){for(var k,l=0,q=0,n=0,t=0,r=0,m=0,v=0,w=0,p=h.matrixWorldInverse,z=0,I=f.length;z<I;z++){var B=f[z];k=B.color;var J=B.intensity,ta=B.distance,za=B.shadow&&B.shadow.map?B.shadow.map.texture:null;if(B.isAmbientLight)l+=k.r*J,q+=k.g*J,n+=k.b*J;else if(B.isDirectionalLight){h=a.get(B);h.color.copy(B.color).multiplyScalar(B.intensity);h.direction.setFromMatrixPosition(B.matrixWorld);c.setFromMatrixPosition(B.target.matrixWorld);h.direction.sub(c);h.direction.transformDirection(p);if(h.shadow=B.castShadow)k=
16027 B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize;b.directionalShadowMap[t]=za;b.directionalShadowMatrix[t]=B.shadow.matrix;b.directional[t]=h;t++}else if(B.isSpotLight){h=a.get(B);h.position.setFromMatrixPosition(B.matrixWorld);h.position.applyMatrix4(p);h.color.copy(k).multiplyScalar(J);h.distance=ta;h.direction.setFromMatrixPosition(B.matrixWorld);c.setFromMatrixPosition(B.target.matrixWorld);h.direction.sub(c);h.direction.transformDirection(p);h.coneCos=Math.cos(B.angle);
16028 h.penumbraCos=Math.cos(B.angle*(1-B.penumbra));h.decay=0===B.distance?0:B.decay;if(h.shadow=B.castShadow)k=B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize;b.spotShadowMap[m]=za;b.spotShadowMatrix[m]=B.shadow.matrix;b.spot[m]=h;m++}else if(B.isRectAreaLight)h=a.get(B),h.color.copy(k).multiplyScalar(J/(B.width*B.height)),h.position.setFromMatrixPosition(B.matrixWorld),h.position.applyMatrix4(p),e.identity(),d.copy(B.matrixWorld),d.premultiply(p),e.extractRotation(d),h.halfWidth.set(.5*
16029 B.width,0,0),h.halfHeight.set(0,.5*B.height,0),h.halfWidth.applyMatrix4(e),h.halfHeight.applyMatrix4(e),b.rectArea[v]=h,v++;else if(B.isPointLight){h=a.get(B);h.position.setFromMatrixPosition(B.matrixWorld);h.position.applyMatrix4(p);h.color.copy(B.color).multiplyScalar(B.intensity);h.distance=B.distance;h.decay=0===B.distance?0:B.decay;if(h.shadow=B.castShadow)k=B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize,h.shadowCameraNear=k.camera.near,h.shadowCameraFar=k.camera.far;
16030 b.pointShadowMap[r]=za;b.pointShadowMatrix[r]=B.shadow.matrix;b.point[r]=h;r++}else B.isHemisphereLight&&(h=a.get(B),h.direction.setFromMatrixPosition(B.matrixWorld),h.direction.transformDirection(p),h.direction.normalize(),h.skyColor.copy(B.color).multiplyScalar(J),h.groundColor.copy(B.groundColor).multiplyScalar(J),b.hemi[w]=h,w++)}b.ambient[0]=l;b.ambient[1]=q;b.ambient[2]=n;b.directional.length=t;b.spot.length=m;b.rectArea.length=v;b.point.length=r;b.hemi.length=w;b.hash=t+","+r+","+m+","+v+","+
16031 w+","+g.length},state:b}}function bg(a,b){var c={};return{update:function(d){var e=b.frame,f=d.geometry,g=a.get(d,f);c[g.id]!==e&&(f.isGeometry&&g.updateFromObject(d),a.update(g),c[g.id]=e);return g},clear:function(){c={}}}}function cg(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Ke(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);!1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");
16032 ""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),cg(c));return d}function Le(a){switch(a){case 3E3:return["Linear","( value )"];case 3001:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+
16033 a);}}function Rd(a,b){b=Le(b);return"vec4 "+a+"( vec4 value ) { return "+b[0]+"ToLinear"+b[1]+"; }"}function dg(a,b){b=Le(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+b[0]+b[1]+"; }"}function eg(a,b){switch(b){case 1:b="Linear";break;case 2:b="Reinhard";break;case 3:b="Uncharted2";break;case 4:b="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+b);}return"vec3 "+a+"( vec3 color ) { return "+b+"ToneMapping( color ); }"}function fg(a,b,c){a=a||{};return[a.derivatives||
16034 b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(Bc).join("\n")}function gg(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+
16035 c+" "+d)}return b.join("\n")}function Bc(a){return""!==a}function Me(a,b){return a.replace(/NUM_DIR_LIGHTS/g,b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function Sd(a){return a.replace(/^[ \t]*#include +<([\w\d.]+)>/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,
16036 function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function hg(a,b,c,d,e,f){var g=a.context,h=d.defines,k=e.vertexShader,l=e.fragmentShader,q="SHADOWMAP_TYPE_BASIC";1===f.shadowMapType?q="SHADOWMAP_TYPE_PCF":2===f.shadowMapType&&(q="SHADOWMAP_TYPE_PCF_SOFT");var n="ENVMAP_TYPE_CUBE",t="ENVMAP_MODE_REFLECTION",r="ENVMAP_BLENDING_MULTIPLY";if(f.envMap){switch(d.envMap.mapping){case 301:case 302:n="ENVMAP_TYPE_CUBE";break;case 306:case 307:n="ENVMAP_TYPE_CUBE_UV";
16037 break;case 303:case 304:n="ENVMAP_TYPE_EQUIREC";break;case 305:n="ENVMAP_TYPE_SPHERE"}switch(d.envMap.mapping){case 302:case 304:t="ENVMAP_MODE_REFRACTION"}switch(d.combine){case 0:r="ENVMAP_BLENDING_MULTIPLY";break;case 1:r="ENVMAP_BLENDING_MIX";break;case 2:r="ENVMAP_BLENDING_ADD"}}var m=0<a.gammaFactor?a.gammaFactor:1,v=fg(d.extensions,f,b),w=gg(h),p=g.createProgram();d.isRawShaderMaterial?(h=[w].filter(Bc).join("\n"),0<h.length&&(h+="\n"),b=[v,w].filter(Bc).join("\n"),0<b.length&&(b+="\n")):(h=
16038 ["precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,w,f.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+m,"#define MAX_BONES "+f.maxBones,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+t:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":
16039 "",f.normalMap?"#define USE_NORMALMAP":"",f.displacementMap&&f.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":"",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.flatShading?"#define FLAT_SHADED":"",f.skinning?"#define USE_SKINNING":"",f.useVertexTexture?"#define BONE_TEXTURE":"",f.morphTargets?"#define USE_MORPHTARGETS":"",f.morphNormals&&
16040 !1===f.flatShading?"#define USE_MORPHNORMALS":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+q:"",f.sizeAttenuation?"#define USE_SIZEATTENUATION":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;",
16041 "uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;",
16042 "\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(Bc).join("\n"),b=[v,"precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,w,f.alphaTest?"#define ALPHATEST "+f.alphaTest:
16043 "","#define GAMMA_FACTOR "+m,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+n:"",f.envMap?"#define "+t:"",f.envMap?"#define "+r:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":"",f.normalMap?"#define USE_NORMALMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":
16044 "",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.gradientMap?"#define USE_GRADIENTMAP":"",f.flatShading?"#define FLAT_SHADED":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(f.numClippingPlanes-f.numClipIntersection),f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+q:"",f.premultipliedAlpha?
16045 "#define PREMULTIPLIED_ALPHA":"",f.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",f.envMap&&b.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==f.toneMapping?"#define TONE_MAPPING":"",0!==f.toneMapping?W.tonemapping_pars_fragment:"",0!==f.toneMapping?eg("toneMapping",f.toneMapping):
16046 "",f.dithering?"#define DITHERING":"",f.outputEncoding||f.mapEncoding||f.envMapEncoding||f.emissiveMapEncoding?W.encodings_pars_fragment:"",f.mapEncoding?Rd("mapTexelToLinear",f.mapEncoding):"",f.envMapEncoding?Rd("envMapTexelToLinear",f.envMapEncoding):"",f.emissiveMapEncoding?Rd("emissiveMapTexelToLinear",f.emissiveMapEncoding):"",f.outputEncoding?dg("linearToOutputTexel",f.outputEncoding):"",f.depthPacking?"#define DEPTH_PACKING "+d.depthPacking:"","\n"].filter(Bc).join("\n"));k=Sd(k);k=Me(k,f);
16047 l=Sd(l);l=Me(l,f);d.isShaderMaterial||(k=Ne(k),l=Ne(l));l=b+l;k=Ke(g,g.VERTEX_SHADER,h+k);l=Ke(g,g.FRAGMENT_SHADER,l);g.attachShader(p,k);g.attachShader(p,l);void 0!==d.index0AttributeName?g.bindAttribLocation(p,0,d.index0AttributeName):!0===f.morphTargets&&g.bindAttribLocation(p,0,"position");g.linkProgram(p);f=g.getProgramInfoLog(p);e=g.getShaderInfoLog(k);q=g.getShaderInfoLog(l);t=n=!0;if(!1===g.getProgramParameter(p,g.LINK_STATUS))n=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),
16048 "gl.VALIDATE_STATUS",g.getProgramParameter(p,g.VALIDATE_STATUS),"gl.getProgramInfoLog",f,e,q);else if(""!==f)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",f);else if(""===e||""===q)t=!1;t&&(this.diagnostics={runnable:n,material:d,programLog:f,vertexShader:{log:e,prefix:h},fragmentShader:{log:q,prefix:b}});g.deleteShader(k);g.deleteShader(l);var z;this.getUniforms=function(){void 0===z&&(z=new gb(g,p,a));return z};var I;this.getAttributes=function(){if(void 0===I){for(var a={},b=g.getProgramParameter(p,
16049 g.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=g.getActiveAttrib(p,c).name;a[d]=g.getAttribLocation(p,d)}I=a}return I};this.destroy=function(){g.deleteProgram(p);this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=ig++;this.code=c;this.usedTimes=1;
16050 this.program=p;this.vertexShader=k;this.fragmentShader=l;return this}function jg(a,b,c){function d(a,b){if(a)a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding);else var c=3E3;3E3===c&&b&&(c=3007);return c}var e=[],f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",
16051 MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow"},g="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap displacementMap specularMap roughnessMap metalnessMap gradientMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights numRectAreaLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking dithering".split(" ");
16052 this.getParameters=function(b,e,g,q,n,t,r){var h=f[b.type];if(r.isSkinnedMesh){var l=r.skeleton.bones;if(c.floatVertexTextures)l=1024;else{var k=Math.min(Math.floor((c.maxVertexUniforms-20)/4),l.length);k<l.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+l.length+" bones. This GPU supports "+k+"."),l=0):l=k}}else l=0;k=c.precision;null!==b.precision&&(k=c.getMaxPrecision(b.precision),k!==b.precision&&console.warn("THREE.WebGLProgram.getParameters:",b.precision,"not supported, using",k,"instead."));
16053 var m=a.getRenderTarget();return{shaderID:h,precision:k,supportsVertexTextures:c.vertexTextures,outputEncoding:d(m?m.texture:null,a.gammaOutput),map:!!b.map,mapEncoding:d(b.map,a.gammaInput),envMap:!!b.envMap,envMapMode:b.envMap&&b.envMap.mapping,envMapEncoding:d(b.envMap,a.gammaInput),envMapCubeUV:!!b.envMap&&(306===b.envMap.mapping||307===b.envMap.mapping),lightMap:!!b.lightMap,aoMap:!!b.aoMap,emissiveMap:!!b.emissiveMap,emissiveMapEncoding:d(b.emissiveMap,a.gammaInput),bumpMap:!!b.bumpMap,normalMap:!!b.normalMap,
16054 displacementMap:!!b.displacementMap,roughnessMap:!!b.roughnessMap,metalnessMap:!!b.metalnessMap,specularMap:!!b.specularMap,alphaMap:!!b.alphaMap,gradientMap:!!b.gradientMap,combine:b.combine,vertexColors:b.vertexColors,fog:!!q,useFog:b.fog,fogExp:q&&q.isFogExp2,flatShading:b.flatShading,sizeAttenuation:b.sizeAttenuation,logarithmicDepthBuffer:c.logarithmicDepthBuffer,skinning:b.skinning&&0<l,maxBones:l,useVertexTexture:c.floatVertexTextures,morphTargets:b.morphTargets,morphNormals:b.morphNormals,
16055 maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:e.directional.length,numPointLights:e.point.length,numSpotLights:e.spot.length,numRectAreaLights:e.rectArea.length,numHemiLights:e.hemi.length,numClippingPlanes:n,numClipIntersection:t,dithering:b.dithering,shadowMapEnabled:a.shadowMap.enabled&&r.receiveShadow&&0<g.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:b.premultipliedAlpha,
16056 alphaTest:b.alphaTest,doubleSided:2===b.side,flipSided:1===b.side,depthPacking:void 0!==b.depthPacking?b.depthPacking:!1}};this.getProgramCode=function(b,c){var d=[];c.shaderID?d.push(c.shaderID):(d.push(b.fragmentShader),d.push(b.vertexShader));if(void 0!==b.defines)for(var e in b.defines)d.push(e),d.push(b.defines[e]);for(e=0;e<g.length;e++)d.push(c[g[e]]);d.push(b.onBeforeCompile.toString());d.push(a.gammaOutput);return d.join()};this.acquireProgram=function(c,d,f,g){for(var h,l=0,k=e.length;l<
16057 k;l++){var q=e[l];if(q.code===g){h=q;++h.usedTimes;break}}void 0===h&&(h=new hg(a,b,g,c,d,f),e.push(h));return h};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=e.indexOf(a);e[b]=e[e.length-1];e.pop();a.destroy()}};this.programs=e}function kg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||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,
16058 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);
16059 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),
16060 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(0<b.version&&t.__version!==b.version){var r=b.image;if(void 0===r)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===r.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===t.__webglInit&&(t.__webglInit=!0,b.addEventListener("dispose",n),t.__webglTexture=
16061 a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_2D,t.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var u=h(b.image,e.maxTextureSize);(1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(u)&&(q=u,q instanceof HTMLImageElement||q instanceof HTMLCanvasElement||q instanceof ImageBitmap?(r=document.createElementNS("http://www.w3.org/1999/xhtml",
16062 "canvas"),r.width=R.floorPowerOfTwo(q.width),r.height=R.floorPowerOfTwo(q.height),r.getContext("2d").drawImage(q,0,0,r.width,r.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+q.width+"x"+q.height+"). Resized to "+r.width+"x"+r.height,q),u=r):u=q);q=k(u);var r=f.convert(b.format),z=f.convert(b.type);m(a.TEXTURE_2D,b,q);var p=b.mipmaps;if(b.isDepthTexture){p=a.DEPTH_COMPONENT;if(1015===b.type){if(!x)throw Error("Float Depth Texture only supported in WebGL2.0");p=a.DEPTH_COMPONENT32F}else x&&
16063 (p=a.DEPTH_COMPONENT16);1026===b.format&&p===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=1012,z=f.convert(b.type));1027===b.format&&(p=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,z=f.convert(b.type)));c.texImage2D(a.TEXTURE_2D,0,p,u.width,u.height,0,r,z,null)}else if(b.isDataTexture)if(0<
16064 p.length&&q){for(var v=0,w=p.length;v<w;v++)u=p[v],c.texImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,r,z,u.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,r,u.width,u.height,0,r,z,u.data);else if(b.isCompressedTexture)for(v=0,w=p.length;v<w;v++)u=p[v],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(r)?c.compressedTexImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,u.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):
16065 c.texImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,r,z,u.data);else if(0<p.length&&q){v=0;for(w=p.length;v<w;v++)u=p[v],c.texImage2D(a.TEXTURE_2D,v,r,r,z,u);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,r,r,z,u);l(b,q)&&a.generateMipmap(a.TEXTURE_2D);t.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_2D,t.__webglTexture)}function m(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f.convert(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,
16066 f.convert(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f.convert(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f.convert(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),1001===g.wrapS&&1001===g.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",g),a.texParameteri(c,a.TEXTURE_MAG_FILTER,q(g.magFilter)),a.texParameteri(c,
16067 a.TEXTURE_MIN_FILTER,q(g.minFilter)),1003!==g.minFilter&&1006!==g.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g));!(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===b.get("OES_texture_half_float_linear")||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,
16068 e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=g.anisotropy)}function p(b,e,g,h){var l=f.convert(e.texture.format),k=f.convert(e.texture.type);c.texImage2D(h,0,l,e.width,e.height,0,l,k,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function w(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),
16069 a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var x="undefined"!==typeof WebGL2RenderingContext&&a instanceof window.WebGL2RenderingContext;this.setTexture2D=r;this.setTextureCube=
16070 function(b,q){var t=d.get(b);if(6===b.image.length)if(0<b.version&&t.__version!==b.version){t.__image__webglTextureCube||(b.addEventListener("dispose",n),t.__image__webglTextureCube=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_CUBE_MAP,t.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);q=b&&b.isCompressedTexture;for(var r=b.image[0]&&b.image[0].isDataTexture,u=[],p=0;6>p;p++)u[p]=q||r?r?b.image[p].image:b.image[p]:h(b.image[p],e.maxCubemapSize);
16071 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;y<C;y++)x=I[y],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(w)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,y,w,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,y,w,x.width,x.height,
16072 0,w,z,x.data);else r?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,w,u[p].width,u[p].height,0,w,z,u[p].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,w,w,z,u[p]);l(b,v)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);t.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+q),c.bindTexture(a.TEXTURE_CUBE_MAP,t.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=
16073 function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",t);f.__webglTexture=a.createTexture();g.textures++;var h=!0===b.isWebGLRenderTargetCube,n=k(b);if(h){e.__webglFramebuffer=[];for(var q=0;6>q;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);
16074 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");
16075 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,
16076 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,
16077 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();
16078 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<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function e(b){!0!==z[b]&&(a.enable(b),z[b]=!0)}function f(b){!1!==z[b]&&(a.disable(b),z[b]=!1)}function g(b,d,g,h,l,k,n,q){0!==b?e(a.BLEND):f(a.BLEND);if(5!==b){if(b!==J||q!==L)switch(b){case 2:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),
16079 a.blendFunc(a.SRC_ALPHA,a.ONE));break;case 3:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR));break;case 4:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR));break;default:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,
16080 a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA))}E=A=ha=C=y=ta=null}else{l=l||d;k=k||g;n=n||h;if(d!==ta||l!==ha)a.blendEquationSeparate(c.convert(d),c.convert(l)),ta=d,ha=l;if(g!==y||h!==C||k!==A||n!==E)a.blendFuncSeparate(c.convert(g),c.convert(h),c.convert(k),c.convert(n)),y=g,C=h,A=k,E=n}J=b;L=q}function h(b){D!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),D=b)}
16081 function k(b){0!==b?(e(a.CULL_FACE),b!==H&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);H=b}function l(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),V!==c||K!==d)a.polygonOffset(c,d),V=c,K=d}else f(a.POLYGON_OFFSET_FILL)}function q(b){void 0===b&&(b=a.TEXTURE0+N-1);R!==b&&(a.activeTexture(b),R=b)}var n=new function(){var b=!1,c=new da,d=null,e=new da(0,0,0,0);return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},
16082 setClear:function(b,d,f,g,h){!0===h&&(b*=g,d*=g,f*=g);c.set(b,d,f,g);!1===e.equals(c)&&(a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;d=null;e.set(-1,0,0,0)}}},t=new function(){var b=!1,c=null,d=null,g=null;return{setTest:function(b){b?e(a.DEPTH_TEST):f(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);
16083 break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);break;case 7:a.depthFunc(a.NOTEQUAL);break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){g!==b&&(a.clearDepth(b),g=b)},reset:function(){b=!1;g=d=c=null}}},r=new function(){var b=!1,c=null,d=null,g=null,h=null,l=null,k=null,n=null,q=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||
16084 (a.stencilMask(d),c=d)},setFunc:function(b,c,e){if(d!==b||g!==c||h!==e)a.stencilFunc(b,c,e),d=b,g=c,h=e},setOp:function(b,c,d){if(l!==b||k!==c||n!==d)a.stencilOp(b,c,d),l=b,k=c,n=d},setLocked:function(a){b=a},setClear:function(b){q!==b&&(a.clearStencil(b),q=b)},reset:function(){b=!1;q=n=k=l=h=g=d=c=null}}},m=a.getParameter(a.MAX_VERTEX_ATTRIBS),p=new Uint8Array(m),w=new Uint8Array(m),x=new Uint8Array(m),z={},I=null,B=null,J=null,ta=null,y=null,C=null,ha=null,A=null,E=null,L=!1,D=null,H=null,M=null,
16085 V=null,K=null,N=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),m=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),aa=1<=parseFloat(m),R=null,P={},Q=new da,G=new da,X={};X[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);X[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);n.setClear(0,0,0,1);t.setClear(1);r.setClear(0);e(a.DEPTH_TEST);t.setFunc(3);h(!1);k(1);e(a.CULL_FACE);e(a.BLEND);g(1);return{buffers:{color:n,depth:t,stencil:r},initAttributes:function(){for(var a=
16086 0,b=p.length;a<b;a++)p[a]=0},enableAttribute:function(c){p[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);0!==x[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),x[c]=0)},enableAttributeAndDivisor:function(c,d){p[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);x[c]!==d&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,d),x[c]=d)},disableUnusedAttributes:function(){for(var b=0,c=w.length;b!==c;++b)w[b]!==p[b]&&(a.disableVertexAttribArray(b),w[b]=0)},enable:e,
16087 disable:f,getCompressedTextureFormats:function(){if(null===I&&(I=[],b.get("WEBGL_compressed_texture_pvrtc")||b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)I.push(c[d]);return I},useProgram:function(b){return B!==b?(a.useProgram(b),B=b,!0):!1},setBlending:g,setMaterial:function(b){2===b.side?f(a.CULL_FACE):e(a.CULL_FACE);h(1===b.side);!0===b.transparent?g(b.blending,b.blendEquation,b.blendSrc,
16088 b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):g(0);t.setFunc(b.depthFunc);t.setTest(b.depthTest);t.setMask(b.depthWrite);n.setMask(b.colorWrite);l(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:h,setCullFace:k,setLineWidth:function(b){b!==M&&(aa&&a.lineWidth(b),M=b)},setPolygonOffset:l,setScissorTest:function(b){b?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:q,bindTexture:function(b,c){null===R&&q();var d=P[R];void 0===d&&(d=
16089 {type:void 0,texture:void 0},P[R]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||X[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,arguments)}catch(fa){console.error("THREE.WebGLState:",fa)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(fa){console.error("THREE.WebGLState:",fa)}},scissor:function(b){!1===Q.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),Q.copy(b))},viewport:function(b){!1===G.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),G.copy(b))},
16090 reset:function(){for(var b=0;b<w.length;b++)1===w[b]&&(a.disableVertexAttribArray(b),w[b]=0);z={};R=I=null;P={};H=D=J=B=null;n.reset();t.reset();r.reset()}}}function ng(a,b,c){function d(b){if("highp"===b){if(0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.HIGH_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision)return"highp";b="mediump"}return"mediump"===b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,
16091 a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f=void 0!==c.precision?c.precision:"highp",g=d(f);g!==f&&(console.warn("THREE.WebGLRenderer:",f,"not supported, using",g,"instead."),f=g);c=!0===c.logarithmicDepthBuffer;var g=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),h=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),k=a.getParameter(a.MAX_TEXTURE_SIZE),l=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),q=a.getParameter(a.MAX_VERTEX_ATTRIBS),n=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),t=a.getParameter(a.MAX_VARYING_VECTORS),
16092 r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),m=0<h,p=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;var c=b.get("EXT_texture_filter_anisotropic");return e=null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0},getMaxPrecision:d,precision:f,logarithmicDepthBuffer:c,maxTextures:g,maxVertexTextures:h,maxTextureSize:k,maxCubemapSize:l,maxAttributes:q,maxVertexUniforms:n,maxVaryings:t,maxFragmentUniforms:r,vertexTextures:m,floatFragmentTextures:p,floatVertexTextures:m&&
16093 p}}function U(a,b,c,d){La.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function nd(a){U.call(this);this.cameras=a||[]}function og(a){function b(){if(null!==d&&d.isPresenting){var b=d.getEyeParameters("left"),e=b.renderWidth,b=b.renderHeight;t=a.getPixelRatio();n=a.getSize();a.setDrawingBufferSize(2*
16094 e,b,1)}else c.enabled&&a.setDrawingBufferSize(n.width,n.height,t)}var c=this,d=null,e=null;"undefined"!==typeof window&&"VRFrameData"in window&&(e=new window.VRFrameData);var f=new K,g=new K,h=new K,k=new U;k.bounds=new da(0,0,.5,1);k.layers.enable(1);var l=new U;l.bounds=new da(.5,0,.5,1);l.layers.enable(2);var q=new nd([k,l]);q.layers.enable(1);q.layers.enable(2);var n,t;"undefined"!==typeof window&&window.addEventListener("vrdisplaypresentchange",b,!1);this.standing=this.enabled=!1;this.getDevice=
16095 function(){return d};this.setDevice=function(a){void 0!==a&&(d=a)};this.getCamera=function(a){if(null===d)return a;d.depthNear=a.near;d.depthFar=a.far;d.getFrameData(e);var b=e.pose;null!==b.position?a.position.fromArray(b.position):a.position.set(0,0,0);null!==b.orientation&&a.quaternion.fromArray(b.orientation);a.updateMatrixWorld();b=d.stageParameters;this.standing&&b&&(g.fromArray(b.sittingToStandingTransform),h.getInverse(g),a.matrixWorld.multiply(g),a.matrixWorldInverse.multiply(h));if(!1===
16096 d.isPresenting)return a;k.near=a.near;l.near=a.near;k.far=a.far;l.far=a.far;q.matrixWorld.copy(a.matrixWorld);q.matrixWorldInverse.copy(a.matrixWorldInverse);k.matrixWorldInverse.fromArray(e.leftViewMatrix);l.matrixWorldInverse.fromArray(e.rightViewMatrix);this.standing&&b&&(k.matrixWorldInverse.multiply(h),l.matrixWorldInverse.multiply(h));a=a.parent;null!==a&&(f.getInverse(a.matrixWorld),k.matrixWorldInverse.multiply(f),l.matrixWorldInverse.multiply(f));k.matrixWorld.getInverse(k.matrixWorldInverse);
16097 l.matrixWorld.getInverse(l.matrixWorldInverse);k.projectionMatrix.fromArray(e.leftProjectionMatrix);l.projectionMatrix.fromArray(e.rightProjectionMatrix);q.projectionMatrix.copy(k.projectionMatrix);a=d.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&k.bounds.fromArray(a.leftBounds),null!==a.rightBounds&&4===a.rightBounds.length&&l.bounds.fromArray(a.rightBounds));return q};this.getStandingMatrix=function(){return g};this.submitFrame=function(){d&&d.isPresenting&&d.submitFrame()};
16098 this.dispose=function(){"undefined"!==typeof window&&window.removeEventListener("vrdisplaypresentchange",b)}}function pg(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];switch(c){case "WEBGL_depth_texture":var d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||a.getExtension("WEBKIT_WEBGL_depth_texture");break;case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||
16099 a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");
16100 break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function qg(){function a(){l.value!==d&&(l.value=d,l.needsUpdate=0<e);c.numPlanes=e;c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){g=l.value;if(!0!==e||null===g){e=d+4*f;b=b.matrixWorldInverse;k.getNormalMatrix(b);if(null===g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+
16101 3]=h.constant}l.value=g;l.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new Aa,k=new ra,l={value:null,needsUpdate:!1};this.uniform=l;this.numIntersection=this.numPlanes=0;this.init=function(a,c,g){var h=0!==a.length||c||0!==e||f;f=c;d=b(a,g,0);e=a.length;return h};this.beginShadows=function(){g=!0;b(null)};this.endShadows=function(){g=!1;a()};this.setState=function(c,h,k,r,m,p){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var n=4*k,q=m.clippingState||null;
16102 l.value=q;q=b(c,r,n,p);for(c=0;c!==n;++c)q[c]=d[c];m.clippingState=q;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Pe(a,b){return{convert:function(c){if(1E3===c)return a.REPEAT;if(1001===c)return a.CLAMP_TO_EDGE;if(1002===c)return a.MIRRORED_REPEAT;if(1003===c)return a.NEAREST;if(1004===c)return a.NEAREST_MIPMAP_NEAREST;if(1005===c)return a.NEAREST_MIPMAP_LINEAR;if(1006===c)return a.LINEAR;if(1007===c)return a.LINEAR_MIPMAP_NEAREST;if(1008===c)return a.LINEAR_MIPMAP_LINEAR;
16103 if(1009===c)return a.UNSIGNED_BYTE;if(1017===c)return a.UNSIGNED_SHORT_4_4_4_4;if(1018===c)return a.UNSIGNED_SHORT_5_5_5_1;if(1019===c)return a.UNSIGNED_SHORT_5_6_5;if(1010===c)return a.BYTE;if(1011===c)return a.SHORT;if(1012===c)return a.UNSIGNED_SHORT;if(1013===c)return a.INT;if(1014===c)return a.UNSIGNED_INT;if(1015===c)return a.FLOAT;if(1016===c){var d=b.get("OES_texture_half_float");if(null!==d)return d.HALF_FLOAT_OES}if(1021===c)return a.ALPHA;if(1022===c)return a.RGB;if(1023===c)return a.RGBA;
16104 if(1024===c)return a.LUMINANCE;if(1025===c)return a.LUMINANCE_ALPHA;if(1026===c)return a.DEPTH_COMPONENT;if(1027===c)return a.DEPTH_STENCIL;if(100===c)return a.FUNC_ADD;if(101===c)return a.FUNC_SUBTRACT;if(102===c)return a.FUNC_REVERSE_SUBTRACT;if(200===c)return a.ZERO;if(201===c)return a.ONE;if(202===c)return a.SRC_COLOR;if(203===c)return a.ONE_MINUS_SRC_COLOR;if(204===c)return a.SRC_ALPHA;if(205===c)return a.ONE_MINUS_SRC_ALPHA;if(206===c)return a.DST_ALPHA;if(207===c)return a.ONE_MINUS_DST_ALPHA;
16105 if(208===c)return a.DST_COLOR;if(209===c)return a.ONE_MINUS_DST_COLOR;if(210===c)return a.SRC_ALPHA_SATURATE;if(2001===c||2002===c||2003===c||2004===c)if(d=b.get("WEBGL_compressed_texture_s3tc"),null!==d){if(2001===c)return d.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===c)return d.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===c)return d.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===c)return d.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===c||2101===c||2102===c||2103===c)if(d=b.get("WEBGL_compressed_texture_pvrtc"),null!==
16106 d){if(2100===c)return d.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===c)return d.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(2102===c)return d.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===c)return d.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===c&&(d=b.get("WEBGL_compressed_texture_etc1"),null!==d))return d.COMPRESSED_RGB_ETC1_WEBGL;if(103===c||104===c)if(d=b.get("EXT_blend_minmax"),null!==d){if(103===c)return d.MIN_EXT;if(104===c)return d.MAX_EXT}return 1020===c&&(d=b.get("WEBGL_depth_texture"),null!==d)?d.UNSIGNED_INT_24_8_WEBGL:
16107 0}}}function Wd(a){function b(){ia=new pg(F);ia.get("WEBGL_depth_texture");ia.get("OES_texture_float");ia.get("OES_texture_float_linear");ia.get("OES_texture_half_float");ia.get("OES_texture_half_float_linear");ia.get("OES_standard_derivatives");ia.get("OES_element_index_uint");ia.get("ANGLE_instanced_arrays");oa=new Pe(F,ia);Z=new ng(F,ia,a);ba=new mg(F,ia,oa);ba.scissor(S.copy(ea).multiplyScalar(O));ba.viewport(Q.copy(ca).multiplyScalar(O));U=new lg;T=new kg(F,ia,ba,U,Z,oa,Vd);na=new Mf(F);pa=new Zf(F,
16108 na,Vd);ra=new bg(pa,Ra);va=new Wf(F);ma=new jg(L,ia,Z);sa=new ag;qa=new Uf;ja=new Qf(L,ba,pa,J);wa=new Yf(F,ia,Ra);xa=new Xf(F,ia,Ra);ya=new Jf(L,F,ba,T,Z);Aa=new Kf(L,F,ba,T,Z);L.info.programs=ma.programs;L.context=F;L.capabilities=Z;L.extensions=ia;L.properties=U;L.renderLists=qa;L.state=ba}function c(a){a.preventDefault();console.log("THREE.WebGLRenderer: Context Lost.");Y=!0}function d(){console.log("THREE.WebGLRenderer: Context Restored.");Y=!1;b()}function e(a){a=a.target;a.removeEventListener("dispose",
16109 e);f(a);U.remove(a)}function f(a){var b=U.get(a).program;a.program=void 0;void 0!==b&&ma.releaseProgram(b)}function g(a,b,c){a.render(function(a){L.renderBufferImmediate(a,b,c)})}function h(a){null!==Ba&&Ba(a);(a=ka.getDevice())&&a.isPresenting?a.requestAnimationFrame(h):window.requestAnimationFrame(h)}function k(a,b,c){if(!1!==a.visible){if(a.layers.test(b.layers))if(a.isLight)y.push(a),a.castShadow&&C.push(a);else if(a.isSprite)a.frustumCulled&&!Td.intersectsSprite(a)||D.push(a);else if(a.isLensFlare)Va.push(a);
16110 else if(a.isImmediateRenderObject)c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(md),A.push(a,null,a.material,Nb.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||Td.intersectsObject(a)){c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(md);var d=ra.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<h;g++){var l=f[g],n=e[l.materialIndex];n&&n.visible&&A.push(a,d,n,Nb.z,l)}else e.visible&&A.push(a,d,e,
16111 Nb.z,null)}a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function l(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,l=g.geometry,k=void 0===d?g.material:d,g=g.group;if(c.isArrayCamera){aa=c;for(var n=c.cameras,t=0,r=n.length;t<r;t++){var m=n[t];if(h.layers.test(m.layers)){var u=m.bounds;ba.viewport(Q.set(u.x*X,u.y*fa,u.z*X,u.w*fa).multiplyScalar(O));q(h,b,m,l,k,g)}}}else aa=null,q(h,b,c,l,k,g)}}function q(a,b,c,d,e,f){a.onBeforeRender(L,b,c,d,e,f);a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,
16112 a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);if(a.isImmediateRenderObject){ba.setMaterial(e);var h=t(c,b.fog,e,a);N="";g(a,h,e)}else L.renderBufferDirect(c,b.fog,d,e,a,f);a.onAfterRender(L,b,c,d,e,f)}function n(a,b,c){var d=U.get(a);c=ma.getParameters(a,sa.state,C,b,Fa.numPlanes,Fa.numIntersection,c);var g=ma.getProgramCode(a,c),h=d.program,l=!0;if(void 0===h)a.addEventListener("dispose",e);else if(h.code!==g)f(a);else{if(void 0!==c.shaderID)return;l=!1}l&&(c.shaderID?(h=mb[c.shaderID],
16113 d.shader={name:a.type,uniforms:Ea.clone(h.uniforms),vertexShader:h.vertexShader,fragmentShader:h.fragmentShader}):d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.onBeforeCompile(d.shader),h=ma.acquireProgram(a,d.shader,c,g),d.program=h,a.program=h);c=h.getAttributes();if(a.morphTargets)for(g=a.numSupportedMorphTargets=0;g<L.maxMorphTargets;g++)0<=c["morphTarget"+g]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(g=a.numSupportedMorphNormals=
16114 0;g<L.maxMorphNormals;g++)0<=c["morphNormal"+g]&&a.numSupportedMorphNormals++;c=d.shader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=Fa.numPlanes,d.numIntersection=Fa.numIntersection,c.clippingPlanes=Fa.uniform;d.fog=b;d.lightsHash=sa.state.hash;a.lights&&(c.ambientLightColor.value=sa.state.ambient,c.directionalLights.value=sa.state.directional,c.spotLights.value=sa.state.spot,c.rectAreaLights.value=sa.state.rectArea,c.pointLights.value=sa.state.point,
16115 c.hemisphereLights.value=sa.state.hemi,c.directionalShadowMap.value=sa.state.directionalShadowMap,c.directionalShadowMatrix.value=sa.state.directionalShadowMatrix,c.spotShadowMap.value=sa.state.spotShadowMap,c.spotShadowMatrix.value=sa.state.spotShadowMatrix,c.pointShadowMap.value=sa.state.pointShadowMap,c.pointShadowMatrix.value=sa.state.pointShadowMatrix);a=d.program.getUniforms();a=gb.seqWithValue(a.seq,c);d.uniformsList=a}function t(a,b,c,d){G=0;var e=U.get(c);ga&&(Ud||a!==P)&&Fa.setState(c.clippingPlanes,
16116 c.clipIntersection,c.clipShadows,a,e,a===P&&c.id===V);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:c.lights&&e.lightsHash!==sa.state.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===Fa.numPlanes&&e.numIntersection===Fa.numIntersection||(c.needsUpdate=!0));c.needsUpdate&&(n(c,b,d),c.needsUpdate=!1);var f=!1,g=!1,h=!1,l=e.program,k=l.getUniforms(),q=e.shader.uniforms;ba.useProgram(l.program)&&(h=g=f=!0);c.id!==V&&(V=c.id,g=!0);if(f||
16117 a!==P){k.setValue(F,"projectionMatrix",a.projectionMatrix);Z.logarithmicDepthBuffer&&k.setValue(F,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));P!==(aa||a)&&(P=aa||a,h=g=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)f=k.map.cameraPosition,void 0!==f&&f.setValue(F,Nb.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&k.setValue(F,"viewMatrix",
16118 a.matrixWorldInverse)}if(c.skinning&&(k.setOptional(F,d,"bindMatrix"),k.setOptional(F,d,"bindMatrixInverse"),a=d.skeleton))if(f=a.bones,Z.floatVertexTextures){if(void 0===a.boneTexture){var f=Math.sqrt(4*f.length),f=R.ceilPowerOfTwo(f),f=Math.max(f,4),t=new Float32Array(f*f*4);t.set(a.boneMatrices);var u=new fb(t,f,f,1023,1015);a.boneMatrices=t;a.boneTexture=u;a.boneTextureSize=f}k.setValue(F,"boneTexture",a.boneTexture);k.setValue(F,"boneTextureSize",a.boneTextureSize)}else k.setOptional(F,a,"boneMatrices");
16119 g&&(k.setValue(F,"toneMappingExposure",L.toneMappingExposure),k.setValue(F,"toneMappingWhitePoint",L.toneMappingWhitePoint),c.lights&&(g=h,q.ambientLightColor.needsUpdate=g,q.directionalLights.needsUpdate=g,q.pointLights.needsUpdate=g,q.spotLights.needsUpdate=g,q.rectAreaLights.needsUpdate=g,q.hemisphereLights.needsUpdate=g),b&&c.fog&&(q.fogColor.value=b.color,b.isFog?(q.fogNear.value=b.near,q.fogFar.value=b.far):b.isFogExp2&&(q.fogDensity.value=b.density)),c.isMeshBasicMaterial?r(q,c):c.isMeshLambertMaterial?
16120 (r(q,c),c.emissiveMap&&(q.emissiveMap.value=c.emissiveMap)):c.isMeshPhongMaterial?(r(q,c),c.isMeshToonMaterial?(m(q,c),c.gradientMap&&(q.gradientMap.value=c.gradientMap)):m(q,c)):c.isMeshStandardMaterial?(r(q,c),c.isMeshPhysicalMaterial&&(q.clearCoat.value=c.clearCoat,q.clearCoatRoughness.value=c.clearCoatRoughness),q.roughness.value=c.roughness,q.metalness.value=c.metalness,c.roughnessMap&&(q.roughnessMap.value=c.roughnessMap),c.metalnessMap&&(q.metalnessMap.value=c.metalnessMap),c.emissiveMap&&
16121 (q.emissiveMap.value=c.emissiveMap),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale),c.normalMap&&(q.normalMap.value=c.normalMap,q.normalScale.value.copy(c.normalScale)),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias),c.envMap&&(q.envMapIntensity.value=c.envMapIntensity)):c.isMeshDepthMaterial?(r(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=
16122 c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isMeshDistanceMaterial?(r(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias),q.referencePosition.value.copy(c.referencePosition),q.nearDistance.value=c.nearDistance,q.farDistance.value=c.farDistance):c.isMeshNormalMaterial?(r(q,c),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale),c.normalMap&&(q.normalMap.value=
16123 c.normalMap,q.normalScale.value.copy(c.normalScale)),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isLineBasicMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,c.isLineDashedMaterial&&(q.dashSize.value=c.dashSize,q.totalSize.value=c.dashSize+c.gapSize,q.scale.value=c.scale)):c.isPointsMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.size.value=c.size*O,q.scale.value=
16124 .5*fa,q.map.value=c.map,null!==c.map&&(!0===c.map.matrixAutoUpdate&&(b=c.map.offset,g=c.map.repeat,h=c.map.center,c.map.matrix.setUvTransform(b.x,b.y,g.x,g.y,c.map.rotation,h.x,h.y)),q.uvTransform.value.copy(c.map.matrix))):c.isShadowMaterial&&(q.color.value=c.color,q.opacity.value=c.opacity),void 0!==q.ltcMat&&(q.ltcMat.value=E.LTC_MAT_TEXTURE),void 0!==q.ltcMag&&(q.ltcMag.value=E.LTC_MAG_TEXTURE),gb.upload(F,e.uniformsList,q,L));k.setValue(F,"modelViewMatrix",d.modelViewMatrix);k.setValue(F,"normalMatrix",
16125 d.normalMatrix);k.setValue(F,"modelMatrix",d.matrixWorld);return l}function r(a,b){a.opacity.value=b.opacity;b.color&&(a.diffuse.value=b.color);b.emissive&&a.emissive.value.copy(b.emissive).multiplyScalar(b.emissiveIntensity);b.map&&(a.map.value=b.map);b.alphaMap&&(a.alphaMap.value=b.alphaMap);b.specularMap&&(a.specularMap.value=b.specularMap);b.envMap&&(a.envMap.value=b.envMap,a.flipEnvMap.value=b.envMap&&b.envMap.isCubeTexture?-1:1,a.reflectivity.value=b.reflectivity,a.refractionRatio.value=b.refractionRatio);
16126 b.lightMap&&(a.lightMap.value=b.lightMap,a.lightMapIntensity.value=b.lightMapIntensity);b.aoMap&&(a.aoMap.value=b.aoMap,a.aoMapIntensity.value=b.aoMapIntensity);if(b.map)var c=b.map;else b.specularMap?c=b.specularMap:b.displacementMap?c=b.displacementMap:b.normalMap?c=b.normalMap:b.bumpMap?c=b.bumpMap:b.roughnessMap?c=b.roughnessMap:b.metalnessMap?c=b.metalnessMap:b.alphaMap?c=b.alphaMap:b.emissiveMap&&(c=b.emissiveMap);if(void 0!==c){c.isWebGLRenderTarget&&(c=c.texture);if(!0===c.matrixAutoUpdate){b=
16127 c.offset;var d=c.repeat,e=c.center;c.matrix.setUvTransform(b.x,b.y,d.x,d.y,c.rotation,e.x,e.y)}a.uvTransform.value.copy(c.matrix)}}function m(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=
16128 b.displacementScale,a.displacementBias.value=b.displacementBias)}console.log("THREE.WebGLRenderer","88");a=a||{};var v=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),w=void 0!==a.context?a.context:null,x=void 0!==a.alpha?a.alpha:!1,z=void 0!==a.depth?a.depth:!0,I=void 0!==a.stencil?a.stencil:!0,B=void 0!==a.antialias?a.antialias:!1,J=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,ta=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,y=
16129 [],C=[],A=null,D=[],Va=[];this.domElement=v;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=!1;this.gammaFactor=2;this.physicallyCorrectLights=this.gammaOutput=this.gammaInput=!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var L=this,Y=!1,H=null,M=null,V=-1,N="",P=null,aa=null,Q=new da,S=new da,W=null,G=0,X=v.width,
16130 fa=v.height,O=1,ca=new da(0,0,X,fa),ea=new da(0,0,X,fa),Oe=!1,Td=new ld,Fa=new qg,ga=!1,Ud=!1,md=new K,Nb=new p,Vd={geometries:0,textures:0},Ra={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:Ra,memory:Vd,programs:null};try{x={alpha:x,depth:z,stencil:I,antialias:B,premultipliedAlpha:J,preserveDrawingBuffer:ta};var F=w||v.getContext("webgl",x)||v.getContext("experimental-webgl",x);if(null===F){if(null!==v.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";
16131 throw"Error creating WebGL context.";}void 0===F.getShaderPrecisionFormat&&(F.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});v.addEventListener("webglcontextlost",c,!1);v.addEventListener("webglcontextrestored",d,!1)}catch(rg){console.error("THREE.WebGLRenderer: "+rg)}var ia,Z,ba,U,T,na,pa,ra,sa,ma,qa,ja,va,wa,xa,ya,Aa,oa;b();var ka=new og(L);this.vr=ka;var Ca=new Ie(L,ra,Z.maxTextureSize);this.shadowMap=Ca;this.getContext=function(){return F};this.getContextAttributes=
16132 function(){return F.getContextAttributes()};this.forceContextLoss=function(){var a=ia.get("WEBGL_lose_context");a&&a.loseContext()};this.forceContextRestore=function(){var a=ia.get("WEBGL_lose_context");a&&a.restoreContext()};this.getPixelRatio=function(){return O};this.setPixelRatio=function(a){void 0!==a&&(O=a,this.setSize(X,fa,!1))};this.getSize=function(){return{width:X,height:fa}};this.setSize=function(a,b,c){var d=ka.getDevice();d&&d.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):
16133 (X=a,fa=b,v.width=a*O,v.height=b*O,!1!==c&&(v.style.width=a+"px",v.style.height=b+"px"),this.setViewport(0,0,a,b))};this.getDrawingBufferSize=function(){return{width:X*O,height:fa*O}};this.setDrawingBufferSize=function(a,b,c){X=a;fa=b;O=c;v.width=a*c;v.height=b*c;this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){ca.set(a,fa-b-d,c,d);ba.viewport(Q.copy(ca).multiplyScalar(O))};this.setScissor=function(a,b,c,d){ea.set(a,fa-b-d,c,d);ba.scissor(S.copy(ea).multiplyScalar(O))};this.setScissorTest=
16134 function(a){ba.setScissorTest(Oe=a)};this.getClearColor=function(){return ja.getClearColor()};this.setClearColor=function(){ja.setClearColor.apply(ja,arguments)};this.getClearAlpha=function(){return ja.getClearAlpha()};this.setClearAlpha=function(){ja.setClearAlpha.apply(ja,arguments)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=F.COLOR_BUFFER_BIT;if(void 0===b||b)d|=F.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=F.STENCIL_BUFFER_BIT;F.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};
16135 this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,b,c,d){this.setRenderTarget(a);this.clear(b,c,d)};this.dispose=function(){v.removeEventListener("webglcontextlost",c,!1);v.removeEventListener("webglcontextrestored",d,!1);qa.dispose();ka.dispose()};this.renderBufferImmediate=function(a,b,c){ba.initAttributes();var d=U.get(a);a.hasPositions&&!d.position&&(d.position=F.createBuffer());a.hasNormals&&!d.normal&&(d.normal=F.createBuffer());
16136 a.hasUvs&&!d.uv&&(d.uv=F.createBuffer());a.hasColors&&!d.color&&(d.color=F.createBuffer());b=b.getAttributes();a.hasPositions&&(F.bindBuffer(F.ARRAY_BUFFER,d.position),F.bufferData(F.ARRAY_BUFFER,a.positionArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.position),F.vertexAttribPointer(b.position,3,F.FLOAT,!1,0,0));if(a.hasNormals){F.bindBuffer(F.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&!0===c.flatShading)for(var e=0,f=3*a.count;e<f;e+=9){var g=
16137 a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,l=(g[e+1]+g[e+4]+g[e+7])/3,k=(g[e+2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=l;g[e+2]=k;g[e+3]=h;g[e+4]=l;g[e+5]=k;g[e+6]=h;g[e+7]=l;g[e+8]=k}F.bufferData(F.ARRAY_BUFFER,a.normalArray,F.DYNAMIC_DRAW);ba.enableAttribute(b.normal);F.vertexAttribPointer(b.normal,3,F.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(F.bindBuffer(F.ARRAY_BUFFER,d.uv),F.bufferData(F.ARRAY_BUFFER,a.uvArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.uv),F.vertexAttribPointer(b.uv,2,F.FLOAT,!1,0,0));a.hasColors&&
16138 0!==c.vertexColors&&(F.bindBuffer(F.ARRAY_BUFFER,d.color),F.bufferData(F.ARRAY_BUFFER,a.colorArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.color),F.vertexAttribPointer(b.color,3,F.FLOAT,!1,0,0));ba.disableUnusedAttributes();F.drawArrays(F.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){ba.setMaterial(d);var g=t(a,b,d,e);a=c.id+"_"+g.id+"_"+(!0===d.wireframe);var h=!1;a!==N&&(N=a,h=!0);e.morphTargetInfluences&&(va.update(e,c,d,g),h=!0);var l=c.index,k=c.attributes.position;
16139 b=1;!0===d.wireframe&&(l=pa.getWireframeAttribute(c),b=2);a=wa;if(null!==l){var n=na.get(l);a=xa;a.setIndex(n)}if(h){h=void 0;if(c&&c.isInstancedBufferGeometry&&null===ia.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{void 0===h&&(h=0);ba.initAttributes();var q=c.attributes,g=g.getAttributes(),r=d.defaultAttributeValues;for(J in g){var m=g[J];if(0<=m){var u=
16140 q[J];if(void 0!==u){var p=u.normalized,v=u.itemSize,w=na.get(u);if(void 0!==w){var z=w.buffer,x=w.type,w=w.bytesPerElement;if(u.isInterleavedBufferAttribute){var B=u.data,I=B.stride,u=u.offset;B&&B.isInstancedInterleavedBuffer?(ba.enableAttributeAndDivisor(m,B.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=B.meshPerAttribute*B.count)):ba.enableAttribute(m);F.bindBuffer(F.ARRAY_BUFFER,z);F.vertexAttribPointer(m,v,x,p,I*w,(h*I+u)*w)}else u.isInstancedBufferAttribute?(ba.enableAttributeAndDivisor(m,
16141 u.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=u.meshPerAttribute*u.count)):ba.enableAttribute(m),F.bindBuffer(F.ARRAY_BUFFER,z),F.vertexAttribPointer(m,v,x,p,0,h*v*w)}}else if(void 0!==r&&(p=r[J],void 0!==p))switch(p.length){case 2:F.vertexAttrib2fv(m,p);break;case 3:F.vertexAttrib3fv(m,p);break;case 4:F.vertexAttrib4fv(m,p);break;default:F.vertexAttrib1fv(m,p)}}}ba.disableUnusedAttributes()}null!==l&&F.bindBuffer(F.ELEMENT_ARRAY_BUFFER,n.buffer)}n=0;null!==l?n=l.count:void 0!==
16142 k&&(n=k.count);l=c.drawRange.start*b;k=null!==f?f.start*b:0;var J=Math.max(l,k);f=Math.max(0,Math.min(n,l+c.drawRange.count*b,k+(null!==f?f.count*b:Infinity))-1-J+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)ba.setLineWidth(d.wireframeLinewidth*(null===H?O:1)),a.setMode(F.LINES);else switch(e.drawMode){case 0:a.setMode(F.TRIANGLES);break;case 1:a.setMode(F.TRIANGLE_STRIP);break;case 2:a.setMode(F.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),ba.setLineWidth(d*(null===H?O:1)),e.isLineSegments?
16143 a.setMode(F.LINES):e.isLineLoop?a.setMode(F.LINE_LOOP):a.setMode(F.LINE_STRIP)):e.isPoints&&a.setMode(F.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,J,f):a.render(J,f)}};this.compile=function(a,b){y.length=0;C.length=0;a.traverse(function(a){a.isLight&&(y.push(a),a.castShadow&&C.push(a))});sa.setup(y,C,b);a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)n(b.material[c],a.fog,b);else n(b.material,a.fog,b)})};
16144 var Da=!1,Ba=null;this.animate=function(a){Ba=a;Da||((a=ka.getDevice())&&a.isPresenting?a.requestAnimationFrame(h):window.requestAnimationFrame(h),Da=!0)};this.render=function(a,b,c,d){if(!b||!b.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else if(!Y){N="";V=-1;P=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();ka.enabled&&(b=ka.getCamera(b));md.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);Td.setFromMatrix(md);
16145 y.length=0;C.length=0;D.length=0;Va.length=0;Ud=this.localClippingEnabled;ga=Fa.init(this.clippingPlanes,Ud,b);A=qa.get(a,b);A.init();k(a,b,L.sortObjects);!0===L.sortObjects&&A.sort();ga&&Fa.beginShadows();Ca.render(C,a,b);sa.setup(y,C,b);ga&&Fa.endShadows();Ra.frame++;Ra.calls=0;Ra.vertices=0;Ra.faces=0;Ra.points=0;void 0===c&&(c=null);this.setRenderTarget(c);ja.render(A,a,b,d);d=A.opaque;var e=A.transparent;if(a.overrideMaterial){var f=a.overrideMaterial;d.length&&l(d,a,b,f);e.length&&l(e,a,b,f)}else d.length&&
16146 l(d,a,b),e.length&&l(e,a,b);Aa.render(D,a,b);ya.render(Va,a,b,Q);c&&T.updateRenderTargetMipmap(c);ba.buffers.depth.setTest(!0);ba.buffers.depth.setMask(!0);ba.buffers.color.setMask(!0);ba.setPolygonOffset(!1);ka.enabled&&ka.submitFrame()}};this.setFaceCulling=function(a,b){ba.setCullFace(a);ba.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=G;a>=Z.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+Z.maxTextures);G+=1;return a};
16147 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&&
16148 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&&
16149 (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;
16150 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")?
16151 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.")}}
16152 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";
16153 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."),
16154 this.boneInverses=[],a=0,b=this.bones.length;a<b;a++)this.boneInverses.push(new K)}function pd(){A.call(this);this.type="Bone"}function qd(a,b){pa.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new K;this.bindMatrixInverse=new K;a=this.initBones();a=new Ec(a);this.bind(a,this.matrixWorld);this.normalizeSkinWeights()}function O(a){Q.call(this);this.type="LineBasicMaterial";this.color=new H(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;
16155 this.setValues(a)}function ma(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),new ca(a,b);A.call(this);this.type="Line";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new O({color:16777215*Math.random()})}function ca(a,b){ma.call(this,a,b);this.type="LineSegments"}function rd(a,b){ma.call(this,a,b);this.type="LineLoop"}function Ba(a){Q.call(this);this.type="PointsMaterial";this.color=new H(16777215);
16156 this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Qb(a,b){A.call(this);this.type="Points";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new Ba({color:16777215*Math.random()})}function Fc(){A.call(this);this.type="Group"}function sd(a,b,c,d,e,f,g,h,k){function l(){var a=q.image;a.readyState>=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)}
16157 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!==
16158 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;l<d;l++){var q=k[l];for(c=0;3>c;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=
16159 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;a<e;++a)for(l=r[a],c=l.start,d=l.count,l=c,d=c+d;l<d;l+=3)for(c=0;3>c;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,
16160 l=0,d=k.count/3;l<d;l++)for(c=0;3>c;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=
16161 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;t<c;t++)for(r=0;r<b;r++)a=t*m+r+1,h=(t+1)*m+r+1,k=(t+1)*m+r,d.push(t*m+r,a,k),d.push(a,h,k);this.setIndex(d);this.addAttribute("position",
16162 new y(e,3));this.addAttribute("normal",new y(f,3));this.addAttribute("uv",new y(g,2))}function Ic(a,b,c,d){N.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new qa(a,b,c,d));this.mergeVertices()}function qa(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){b*=3;c.x=a[b+0];c.y=a[b+1];c.z=a[b+2]}function g(a,b,c,d){0>d&&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";
16163 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;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k,l,m=c,x=d,z=g,I=Math.pow(2,a),B=[];for(l=0;l<=I;l++){B[l]=[];var J=m.clone().lerp(z,l/I),y=x.clone().lerp(z,l/I),C=I-l;for(k=0;k<=C;k++)B[l][k]=0===k&&l===I?J:J.clone().lerp(y,k/C)}for(l=0;l<I;l++)for(k=0;k<2*(I-l)-1;k++)m=Math.floor(k/2),0===k%2?(e(B[l][m+1]),e(B[l+1][m]),e(B[l][m])):(e(B[l][m+1]),e(B[l+1][m+
16164 1]),e(B[l+1][m]))}})(d);(function(a){for(var b=new p,c=0;c<h.length;c+=3)b.x=h[c+0],b.y=h[c+1],b.z=h[c+2],b.normalize().multiplyScalar(a),h[c+0]=b.x,h[c+1]=b.y,h[c+2]=b.z})(c);(function(){for(var a=new p,b=0;b<h.length;b+=3)a.x=h[b+0],a.y=h[b+1],a.z=h[b+2],k.push(Math.atan2(a.z,-a.x)/2/Math.PI+.5,1-(Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+.5));for(var a=new p,b=new p,c=new p,d=new p,e=new C,f=new C,m=new C,w=0,x=0;w<h.length;w+=9,x+=6){a.set(h[w+0],h[w+1],h[w+2]);b.set(h[w+3],h[w+4],h[w+
16165 5]);c.set(h[w+6],h[w+7],h[w+8]);e.set(k[x+0],k[x+1]);f.set(k[x+2],k[x+3]);m.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);var z=Math.atan2(d.z,-d.x);g(e,x+0,a,z);g(f,x+2,b,z);g(m,x+4,c,z)}for(a=0;a<k.length;a+=6)b=k[a+0],c=k[a+2],d=k[a+4],e=Math.min(b,c,d),.9<Math.max(b,c,d)&&.1>e&&(.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():
16166 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()}
16167 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,
16168 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,
16169 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,
16170 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,
16171 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;n<b;n++)f(n);f(!1===e?b:0);for(n=0;n<=b;n++)for(t=0;t<=d;t++)l.x=n/b,l.y=t/d,v.push(l.x,l.y);(function(){for(t=
16172 1;t<=b;t++)for(n=1;n<=d;n++){var a=(d+1)*t+(n-1),c=(d+1)*t+n,e=(d+1)*(t-1)+n;w.push((d+1)*(t-1)+(n-1),a,e);w.push(a,c,e)}})();this.setIndex(w);this.addAttribute("position",new y(m,3));this.addAttribute("normal",new y(u,3));this.addAttribute("uv",new y(v,2))}function Oc(a,b,c,d,e,f,g){N.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");
16173 this.fromBufferGeometry(new Yb(a,b,c,d,e,f));this.mergeVertices()}function Yb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}D.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||1;b=b||.4;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=[],k=[],l=[],q=[],n,t=new p,m=new p,u=new p,v=new p,w=new p,x=new p,z=new p;for(n=0;n<=
16174 c;++n){var I=n/c*e*Math.PI*2;g(I,e,f,a,u);g(I+.01,e,f,a,v);x.subVectors(v,u);z.addVectors(v,u);w.crossVectors(x,z);z.crossVectors(w,x);w.normalize();z.normalize();for(I=0;I<=d;++I){var B=I/d*Math.PI*2,J=-b*Math.cos(B),B=b*Math.sin(B);t.x=u.x+(J*z.x+B*w.x);t.y=u.y+(J*z.y+B*w.y);t.z=u.z+(J*z.z+B*w.z);k.push(t.x,t.y,t.z);m.subVectors(t,u).normalize();l.push(m.x,m.y,m.z);q.push(n/c);q.push(I/d)}}for(I=1;I<=c;I++)for(n=1;n<=d;n++)a=(d+1)*I+(n-1),b=(d+1)*I+n,e=(d+1)*(I-1)+n,h.push((d+1)*(I-1)+(n-1),a,e),
16175 h.push(a,b,e);this.setIndex(h);this.addAttribute("position",new y(k,3));this.addAttribute("normal",new y(l,3));this.addAttribute("uv",new y(q,2))}function Pc(a,b,c,d,e){N.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Zb(a,b,c,d,e));this.mergeVertices()}function Zb(a,b,c,d,e){D.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||1;b=b||
16176 .4;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],l=new p,q=new p,n=new p,t,m;for(t=0;t<=c;t++)for(m=0;m<=d;m++){var u=m/d*e,v=t/c*Math.PI*2;q.x=(a+b*Math.cos(v))*Math.cos(u);q.y=(a+b*Math.cos(v))*Math.sin(u);q.z=b*Math.sin(v);g.push(q.x,q.y,q.z);l.x=a*Math.cos(u);l.y=a*Math.sin(u);n.subVectors(q,l).normalize();h.push(n.x,n.y,n.z);k.push(m/d);k.push(t/c)}for(t=1;t<=c;t++)for(m=1;m<=d;m++)a=(d+1)*(t-1)+m-1,b=(d+1)*(t-1)+m,e=(d+1)*t+m,f.push((d+1)*t+m-1,a,e),f.push(a,b,
16177 e);this.setIndex(f);this.addAttribute("position",new y(g,3));this.addAttribute("normal",new y(h,3));this.addAttribute("uv",new y(k,2))}function $a(a,b){N.call(this);this.type="ExtrudeGeometry";this.parameters={shapes:a,options:b};this.fromBufferGeometry(new Ga(a,b));this.mergeVertices()}function Ga(a,b){"undefined"!==typeof a&&(D.call(this),this.type="ExtrudeBufferGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeVertexNormals())}function Qc(a,b){N.call(this);this.type="TextGeometry";
16178 this.parameters={text:a,parameters:b};this.fromBufferGeometry(new $b(a,b));this.mergeVertices()}function $b(a,b){b=b||{};var c=b.font;if(!c||!c.isFont)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new N;a=c.generateShapes(a,b.size,b.curveSegments);b.amount=void 0!==b.height?b.height:50;void 0===b.bevelThickness&&(b.bevelThickness=10);void 0===b.bevelSize&&(b.bevelSize=8);void 0===b.bevelEnabled&&(b.bevelEnabled=!1);Ga.call(this,a,b);this.type="TextBufferGeometry"}
16179 function Rc(a,b,c,d,e,f,g){N.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new ob(a,b,c,d,e,f,g));this.mergeVertices()}function ob(a,b,c,d,e,f,g){D.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||1;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==
16180 d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;var h=f+g,k,l,q=0,n=[],t=new p,m=new p,u=[],v=[],w=[],x=[];for(l=0;l<=c;l++){var z=[],I=l/c;for(k=0;k<=b;k++){var B=k/b;t.x=-a*Math.cos(d+B*e)*Math.sin(f+I*g);t.y=a*Math.cos(f+I*g);t.z=a*Math.sin(d+B*e)*Math.sin(f+I*g);v.push(t.x,t.y,t.z);m.set(t.x,t.y,t.z).normalize();w.push(m.x,m.y,m.z);x.push(B,1-I);z.push(q++)}n.push(z)}for(l=0;l<c;l++)for(k=0;k<b;k++)a=n[l][k+1],d=n[l][k],e=n[l+1][k],g=n[l+1][k+1],(0!==l||0<f)&&u.push(a,d,
16181 g),(l!==c-1||h<Math.PI)&&u.push(d,e,g);this.setIndex(u);this.addAttribute("position",new y(v,3));this.addAttribute("normal",new y(w,3));this.addAttribute("uv",new y(x,2))}function Sc(a,b,c,d,e,f){N.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new ac(a,b,c,d,e,f));this.mergeVertices()}function ac(a,b,c,d,e,f){D.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,
16182 outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||.5;b=b||1;e=void 0!==e?e:0;f=void 0!==f?f:2*Math.PI;c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=[],h=[],k=[],l=[],q=a,n=(b-a)/d,t=new p,m=new C,u,v;for(u=0;u<=d;u++){for(v=0;v<=c;v++)a=e+v/c*f,t.x=q*Math.cos(a),t.y=q*Math.sin(a),h.push(t.x,t.y,t.z),k.push(0,0,1),m.x=(t.x/b+1)/2,m.y=(t.y/b+1)/2,l.push(m.x,m.y);q+=n}for(u=0;u<d;u++)for(b=u*(c+1),v=0;v<c;v++)a=v+b,e=a+c+1,f=a+c+2,q=a+1,g.push(a,e,q),g.push(e,
16183 f,q);this.setIndex(g);this.addAttribute("position",new y(h,3));this.addAttribute("normal",new y(k,3));this.addAttribute("uv",new y(l,2))}function Tc(a,b,c,d){N.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new bc(a,b,c,d));this.mergeVertices()}function bc(a,b,c,d){D.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||2*Math.PI;d=R.clamp(d,
16184 0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new p,l=new C,q;for(q=0;q<=b;q++){var n=c+q*h*d;var t=Math.sin(n),m=Math.cos(n);for(n=0;n<=a.length-1;n++)k.x=a[n].x*t,k.y=a[n].y,k.z=a[n].x*m,f.push(k.x,k.y,k.z),l.x=q/b,l.y=n/(a.length-1),g.push(l.x,l.y)}for(q=0;q<b;q++)for(n=0;n<a.length-1;n++)c=n+q*a.length,h=c+a.length,k=c+a.length+1,l=c+1,e.push(c,h,l),e.push(h,k,l);this.setIndex(e);this.addAttribute("position",new y(f,3));this.addAttribute("uv",new y(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=
16185 this.attributes.normal.array,e=new p,f=new p,g=new p,c=b*a.length*3,n=q=0;q<a.length;q++,n+=3)e.x=d[n+0],e.y=d[n+1],e.z=d[n+2],f.x=d[c+n+0],f.y=d[c+n+1],f.z=d[c+n+2],g.addVectors(e,f).normalize(),d[n+0]=d[c+n+0]=g.x,d[n+1]=d[c+n+1]=g.y,d[n+2]=d[c+n+2]=g.z}function cc(a,b){N.call(this);this.type="ShapeGeometry";"object"===typeof b&&(console.warn("THREE.ShapeGeometry: Options parameter has been removed."),b=b.curveSegments);this.parameters={shapes:a,curveSegments:b};this.fromBufferGeometry(new dc(a,
16186 b));this.mergeVertices()}function dc(a,b){function c(a){var c,h=e.length/3;a=a.extractPoints(b);var l=a.shape,q=a.holes;if(!1===Ha.isClockWise(l))for(l=l.reverse(),a=0,c=q.length;a<c;a++){var m=q[a];!0===Ha.isClockWise(m)&&(q[a]=m.reverse())}var p=Ha.triangulateShape(l,q);a=0;for(c=q.length;a<c;a++)m=q[a],l=l.concat(m);a=0;for(c=l.length;a<c;a++)m=l[a],e.push(m.x,m.y,0),f.push(0,0,1),g.push(m.x,m.y);a=0;for(c=p.length;a<c;a++)l=p[a],d.push(l[0]+h,l[1]+h,l[2]+h),k+=3}D.call(this);this.type="ShapeBufferGeometry";
16187 this.parameters={shapes:a,curveSegments:b};b=b||12;var d=[],e=[],f=[],g=[],h=0,k=0;if(!1===Array.isArray(a))c(a);else for(var l=0;l<a.length;l++)c(a[l]),this.addGroup(h,k,l),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new y(e,3));this.addAttribute("normal",new y(f,3));this.addAttribute("uv",new y(g,2))}function ec(a,b){D.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[];b=Math.cos(R.DEG2RAD*(void 0!==b?b:1));var d=[0,0],e={},f=["a","b","c"];if(a.isBufferGeometry){var g=
16188 new N;g.fromBufferGeometry(a)}else g=a.clone();g.mergeVertices();g.computeFaceNormals();a=g.vertices;g=g.faces;for(var h=0,k=g.length;h<k;h++)for(var l=g[h],q=0;3>q;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",
16189 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),
16190 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;e<d;e++)f=y+e,k=A+e,!0===c?q.push(k,k+1,f):q.push(k+1,k,f),r+=3;l.addGroup(x,r,!0===c?1:2);x+=r}D.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var l=this;a=void 0!==a?a:1;b=void 0!==b?b:1;c=c||1;d=Math.floor(d)||8;e=Math.floor(e)||1;f=void 0!==f?f:
16191 !1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var q=[],n=[],t=[],m=[],u=0,v=[],w=c/2,x=0;(function(){var f,k,r=new p,J=new p,y=0,C=(b-a)/c;for(k=0;k<=e;k++){var A=[],D=k/e,E=D*(b-a)+a;for(f=0;f<=d;f++){var H=f/d,L=H*h+g,Y=Math.sin(L),L=Math.cos(L);J.x=E*Y;J.y=-D*c+w;J.z=E*L;n.push(J.x,J.y,J.z);r.set(Y,C,L).normalize();t.push(r.x,r.y,r.z);m.push(H,1-D);A.push(u++)}v.push(A)}for(f=0;f<d;f++)for(k=0;k<e;k++)r=v[k+1][f],J=v[k+1][f+1],C=v[k][f+1],q.push(v[k][f],r,C),q.push(r,J,C),y+=6;l.addGroup(x,y,0);
16192 x+=y})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(q);this.addAttribute("position",new y(n,3));this.addAttribute("normal",new y(t,3));this.addAttribute("uv",new y(m,2))}function Uc(a,b,c,d,e,f,g){pb.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Vc(a,b,c,d,e,f,g){Sa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,height:b,radialSegments:c,
16193 heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Wc(a,b,c,d){N.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new fc(a,b,c,d));this.mergeVertices()}function fc(a,b,c,d){D.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||1;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=[],f=[],g=[],h=[],k,l=new p,q=new C;f.push(0,
16194 0,0);g.push(0,0,1);h.push(.5,.5);var n=0;for(k=3;n<=b;n++,k+=3){var t=c+n/b*d;l.x=a*Math.cos(t);l.y=a*Math.sin(t);f.push(l.x,l.y,l.z);g.push(0,0,1);q.x=(f[k]/a+1)/2;q.y=(f[k+1]/a+1)/2;h.push(q.x,q.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",new y(f,3));this.addAttribute("normal",new y(g,3));this.addAttribute("uv",new y(h,2))}function gc(a){Q.call(this);this.type="ShadowMaterial";this.color=new H(0);this.opacity=1;this.transparent=this.lights=!0;this.setValues(a)}
16195 function hc(a){oa.call(this,a);this.type="RawShaderMaterial"}function Ma(a){Q.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new H(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=
16196 0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function qb(a){Ma.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ia(a){Q.call(this);this.type="MeshPhongMaterial";
16197 this.color=new H(16777215);this.specular=new H(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=
16198 !1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function rb(a){Ia.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function sb(a){Q.call(this);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=
16199 !1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=!1;this.setValues(a)}function tb(a){Q.call(this);this.type="MeshLambertMaterial";this.color=new H(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=
16200 1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function ub(a){O.call(this);this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(a)}function Yd(a,b,c){var d=this,e=!1,f=0,g=0,h=void 0;this.onStart=void 0;this.onLoad=a;this.onProgress=b;this.onError=c;this.itemStart=function(a){g++;if(!1===e&&void 0!==d.onStart)d.onStart(a,f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,
16201 f,g);if(f===g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)};this.resolveURL=function(a){return h?h(a):a};this.setURLModifier=function(a){h=a}}function Ja(a){this.manager=void 0!==a?a:wa}function Qe(a){this.manager=void 0!==a?a:wa;this._parser=null}function Zd(a){this.manager=void 0!==a?a:wa;this._parser=null}function Xc(a){this.manager=void 0!==a?a:wa}function $d(a){this.manager=void 0!==a?a:wa}function td(a){this.manager=void 0!==a?a:wa}function ga(a,
16202 b){A.call(this);this.type="Light";this.color=new H(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function ud(a,b,c){ga.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(A.DefaultUp);this.updateMatrix();this.groundColor=new H(b)}function vb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new K}function vd(){vb.call(this,new U(50,1,.5,500))}function wd(a,b,c,d,e,f){ga.call(this,a,b);this.type="SpotLight";
16203 this.position.copy(A.DefaultUp);this.updateMatrix();this.target=new A;Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new vd}function xd(a,b,c,d){ga.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=
16204 a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new vb(new U(90,1,.5,500))}function yd(){vb.call(this,new Kb(-5,5,5,-5,.5,500))}function zd(a,b){ga.call(this,a,b);this.type="DirectionalLight";this.position.copy(A.DefaultUp);this.updateMatrix();this.target=new A;this.shadow=new yd}function Ad(a,b){ga.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function Bd(a,b,c,d){ga.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();
16205 this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function xa(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function Cd(a,b,c,d){xa.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function Yc(a,b,c,d){xa.call(this,a,b,c,d)}function Dd(a,b,c,d){xa.call(this,a,b,c,d)}function wb(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===
16206 b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=T.convertArray(b,this.TimeBufferType);this.values=T.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function ic(a,b,c,d){wb.call(this,a,b,c,d)}function Ed(a,b,c,d){xa.call(this,a,b,c,d)}function Zc(a,b,c,d){wb.call(this,a,b,c,d)}function jc(a,b,c,d){wb.call(this,a,b,c,d)}function Fd(a,b,c,d){wb.call(this,a,b,c,d)}function Gd(a,b,c){wb.call(this,a,b,
16207 c)}function Hd(a,b,c,d){wb.call(this,a,b,c,d)}function xb(a,b,c,d){wb.apply(this,a,b,c,d)}function ka(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=R.generateUUID();0>this.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."),
16208 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||
16209 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=
16210 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?
16211 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));
16212 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=
16213 !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=
16214 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)}
16215 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,
16216 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=
16217 {};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=
16218 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."),
16219 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,
16220 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=
16221 a.length;d<e;d++)oe(a[d],b,c,!0)}}function af(a){this.autoStart=void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function bf(a,b,c){this.radius=void 0!==a?a:1;this.phi=void 0!==b?b:0;this.theta=void 0!==c?c:0;return this}function cf(a,b,c){this.radius=void 0!==a?a:1;this.theta=void 0!==b?b:0;this.y=void 0!==c?c:0;return this}function ad(a){A.call(this);this.material=a;this.render=function(){}}function bd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:
16222 16711680;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=3*c.faces.length:c&&c.isBufferGeometry&&(b=c.attributes.normal.count);c=new D;b=new y(6*b,3);c.addAttribute("position",b);ca.call(this,c,new O({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function nc(a,b){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new D;b=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(var c=0,
16223 d=1;32>c;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;c<a.children.length;c++)b.push.apply(b,df(a.children[c]));return b}function oc(a){for(var b=df(a),c=new D,d=[],e=[],f=new H(0,0,1),g=new H(0,1,0),h=0;h<b.length;h++){var k=b[h];k.parent&&k.parent.isBone&&(d.push(0,
16224 0,0),d.push(0,0,0),e.push(f.r,f.g,f.b),e.push(g.r,g.g,g.b))}c.addAttribute("position",new y(d,3));c.addAttribute("color",new y(e,3));d=new O({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});ca.call(this,c,d);this.root=a;this.bones=b;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1}function pc(a,b,c){this.light=a;this.light.updateMatrixWorld();this.color=c;a=new ob(b,4,2);b=new va({wireframe:!0,fog:!1});pa.call(this,a,b);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1;this.update()}
16225 function qc(a,b){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new O({fog:!1});b=new D;b.addAttribute("position",new P(new Float32Array(15),3));this.line=new ma(b,a);this.add(this.line);this.update()}function rc(a,b,c){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;a=new nb(b);a.rotateY(.5*Math.PI);this.material=new va({wireframe:!0,fog:!1});void 0===
16226 this.color&&(this.material.vertexColors=2);b=a.getAttribute("position");b=new Float32Array(3*b.count);a.addAttribute("color",new P(b,3));this.add(new pa(a,this.material));this.update()}function cd(a,b,c,d){a=a||10;b=b||10;c=new H(void 0!==c?c:4473924);d=new H(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,l=0,q=-g;k<=b;k++,q+=f){a.push(-g,0,q,g,0,q);a.push(q,0,-g,q,0,g);var n=k===e?c:d;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3}b=new D;b.addAttribute("position",
16227 new y(a,3));b.addAttribute("color",new y(h,3));c=new O({vertexColors:2});ca.call(this,b,c)}function Kd(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new H(void 0!==e?e:4473924);f=new H(void 0!==f?f:8947848);var g=[],h=[],k;for(k=0;k<=b;k++){var l=k/b*2*Math.PI;var q=Math.sin(l)*a;l=Math.cos(l)*a;g.push(0,0,0);g.push(q,0,l);var n=k&1?e:f;h.push(n.r,n.g,n.b);h.push(n.r,n.g,n.b)}for(k=0;k<=c;k++){n=k&1?e:f;var t=a-a/c*k;for(b=0;b<d;b++)l=b/d*2*Math.PI,q=Math.sin(l)*t,l=Math.cos(l)*t,g.push(q,0,l),h.push(n.r,
16228 n.g,n.b),l=(b+1)/d*2*Math.PI,q=Math.sin(l)*t,l=Math.cos(l)*t,g.push(q,0,l),h.push(n.r,n.g,n.b)}a=new D;a.addAttribute("position",new y(g,3));a.addAttribute("color",new y(h,3));g=new O({vertexColors:2});ca.call(this,a,g)}function dd(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 D;
16229 b=new y(6*b,3);c.addAttribute("position",b);ca.call(this,c,new O({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function sc(a,b,c){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;void 0===b&&(b=1);a=new D;a.addAttribute("position",new y([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));b=new O({fog:!1});this.lightPlane=new ma(a,b);this.add(this.lightPlane);a=new D;a.addAttribute("position",new y([0,0,0,0,0,1],3));this.targetLine=
16230 new ma(a,b);this.add(this.targetLine);this.update()}function ed(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/3-1)}var d=new D,e=new O({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new H(16755200),l=new H(16711680),q=new H(43775),n=new H(16777215),t=new H(3355443);b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);
16231 b("n3","f3",k);b("n4","f4",k);b("p","n1",l);b("p","n2",l);b("p","n3",l);b("p","n4",l);b("u1","u2",q);b("u2","u3",q);b("u3","u1",q);b("c","t",n);b("p","c",t);b("cn1","cn2",t);b("cn3","cn4",t);b("cf1","cf2",t);b("cf3","cf4",t);d.addAttribute("position",new y(f,3));d.addAttribute("color",new y(g,3));ca.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function Db(a,b){this.object=
16232 a;void 0===b&&(b=16776960);a=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]);var c=new Float32Array(24),d=new D;d.setIndex(new P(a,1));d.addAttribute("position",new P(c,3));ca.call(this,d,new O({color:b}));this.matrixAutoUpdate=!1;this.update()}function fd(a,b){this.type="Box3Helper";this.box=a;a=void 0!==b?b:16776960;b=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]);var c=new D;c.setIndex(new P(b,1));c.addAttribute("position",new y([1,1,1,-1,1,1,-1,-1,1,1,-1,
16233 1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3));ca.call(this,c,new O({color:a}));this.geometry.computeBoundingSphere()}function gd(a,b,c){this.type="PlaneHelper";this.plane=a;this.size=void 0===b?1:b;a=void 0!==c?c:16776960;b=new D;b.addAttribute("position",new y([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,0,1,0,0,0],3));b.computeBoundingSphere();ma.call(this,b,new O({color:a}));b=new D;b.addAttribute("position",new y([1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1],3));b.computeBoundingSphere();
16234 this.add(new pa(b,new va({color:a,opacity:.2,transparent:!0,depthWrite:!1})))}function Eb(a,b,c,d,e,f){A.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);void 0===Ld&&(Ld=new D,Ld.addAttribute("position",new y([0,0,0,0,1,0],3)),pe=new Sa(0,.5,1,5,1),pe.translate(0,-.5,0));this.position.copy(b);this.line=new ma(Ld,new O({color:d}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new pa(pe,new va({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);
16235 this.setDirection(a);this.setLength(c,e,f)}function hd(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new D;a.addAttribute("position",new y(b,3));a.addAttribute("color",new y([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new O({vertexColors:2});ca.call(this,a,b)}function qe(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,f,g,h,k){e=k*(g-e);h=k*(h-f);a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},initNonuniformCatmullRom:function(e,f,g,h,k,l,q){e=((f-e)/k-(g-e)/(k+l)+(g-f)/l)*l;h=((g-f)/
16236 l-(h-f)/(l+q)+(h-g)/q)*l;a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},calc:function(e){var f=e*e;return a+b*e+c*f+d*f*e}}}function ya(a,b,c,d){S.call(this);this.type="CatmullRomCurve3";this.points=a||[];this.closed=b||!1;this.curveType=c||"centripetal";this.tension=d||.5}function Fb(a,b,c,d){S.call(this);this.type="CubicBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=c||new p;this.v3=d||new p}function Gb(a,b,c){S.call(this);this.type="QuadraticBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=
16237 c||new p}function db(a,b){S.call(this);this.type="LineCurve3";this.v1=a||new p;this.v2=b||new p}function id(a,b,c,d,e,f){Na.call(this,a,b,c,c,d,e,f);this.type="ArcCurve"}function ef(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ya.call(this,a);this.type="catmullrom";this.closed=!0}function ff(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ya.call(this,a);this.type="catmullrom"}function re(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");
16238 ya.call(this,a);this.type="catmullrom"}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Number.isInteger&&(Number.isInteger=function(a){return"number"===typeof a&&isFinite(a)&&Math.floor(a)===a});void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0<a?1:+a});!1==="name"in Function.prototype&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===
16239 a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,e)&&(b[e]=d[e])}return b}}();Object.assign(ja.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},hasEventListener:function(a,b){if(void 0===this._listeners)return!1;
16240 var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){void 0!==this._listeners&&(a=this._listeners[a],void 0!==a&&(b=a.indexOf(b),-1!==b&&a.splice(b,1)))},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;for(var b=b.slice(0),c=0,d=b.length;c<d;c++)b[c].call(this,a)}}}});var R={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),
16241 b=0,c;return function(){for(var d="",e=0;36>e;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,
16242 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,
16243 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;
16244 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},
16245 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;
16246 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=
16247 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);
16248 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)+
16249 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+=
16250 (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);
16251 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)},
16252 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,
16253 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.");
16254 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]=
16255 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=
16256 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,
16257 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;
16258 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*
16259 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;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=
16260 this.elements,b=a[0],c=a[4],d=a[8],e=a[12],f=a[1],g=a[5],h=a[9],k=a[13],l=a[2],q=a[6],n=a[10],m=a[14];return a[3]*(+e*h*q-d*k*q-e*g*n+c*k*n+d*g*m-c*h*m)+a[7]*(+b*h*m-b*k*n+e*f*n-d*f*m+d*k*l-e*h*l)+a[11]*(+b*k*q-b*g*m-e*f*q+c*f*m+e*g*l-c*k*l)+a[15]*(-d*g*l-b*h*q+b*g*n+d*f*q-c*f*n+c*h*l)},transpose:function(){var a=this.elements;var b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},setPosition:function(a){var b=
16261 this.elements;b[12]=a.x;b[13]=a.y;b[14]=a.z;return this},getInverse:function(a,b){var c=this.elements,d=a.elements;a=d[0];var e=d[1],f=d[2],g=d[3],h=d[4],k=d[5],l=d[6],q=d[7],n=d[8],m=d[9],r=d[10],p=d[11],v=d[12],w=d[13],x=d[14],d=d[15],z=m*x*q-w*r*q+w*l*p-k*x*p-m*l*d+k*r*d,I=v*r*q-n*x*q-v*l*p+h*x*p+n*l*d-h*r*d,B=n*w*q-v*m*q+v*k*p-h*w*p-n*k*d+h*m*d,J=v*m*l-n*w*l-v*k*r+h*w*r+n*k*x-h*m*x,y=a*z+e*I+f*B+g*J;if(0===y){if(!0===b)throw Error("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");
16262 console.warn("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/y;c[0]=z*b;c[1]=(w*r*g-m*x*g-w*f*p+e*x*p+m*f*d-e*r*d)*b;c[2]=(k*x*g-w*l*g+w*f*q-e*x*q-k*f*d+e*l*d)*b;c[3]=(m*l*g-k*r*g-m*f*q+e*r*q+k*f*p-e*l*p)*b;c[4]=I*b;c[5]=(n*x*g-v*r*g+v*f*p-a*x*p-n*f*d+a*r*d)*b;c[6]=(v*l*g-h*x*g-v*f*q+a*x*q+h*f*d-a*l*d)*b;c[7]=(h*r*g-n*l*g+n*f*q-a*r*q-h*f*p+a*l*p)*b;c[8]=B*b;c[9]=(v*m*g-n*w*g-v*e*p+a*w*p+n*e*d-a*m*d)*b;c[10]=(h*w*g-v*k*g+v*e*q-a*w*q-h*e*d+a*k*d)*b;c[11]=
16263 (n*k*g-h*m*g-n*e*q+a*m*q+h*e*p-a*k*p)*b;c[12]=J*b;c[13]=(n*w*f-v*m*f+v*e*r-a*w*r-n*e*x+a*m*x)*b;c[14]=(v*k*f-h*w*f-v*e*l+a*w*l+h*e*x-a*k*x)*b;c[15]=(h*m*f-n*k*f+n*e*l-a*m*l-h*e*r+a*k*r)*b;return this},scale:function(a){var b=this.elements,c=a.x,d=a.y;a=a.z;b[0]*=c;b[4]*=d;b[8]*=a;b[1]*=c;b[5]*=d;b[9]*=a;b[2]*=c;b[6]*=d;b[10]*=a;b[3]*=c;b[7]*=d;b[11]*=a;return this},getMaxScaleOnAxis:function(){var a=this.elements;return Math.sqrt(Math.max(a[0]*a[0]+a[1]*a[1]+a[2]*a[2],a[4]*a[4]+a[5]*a[5]+a[6]*a[6],
16264 a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},makeRotationX:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=
16265 Math.cos(b);b=Math.sin(b);var d=1-c,e=a.x,f=a.y;a=a.z;var g=d*e,h=d*f;this.set(g*e+c,g*f-b*a,g*a+b*f,0,g*f+b*a,h*f+c,h*a-b*e,0,g*a-b*f,h*a+b*e,d*a*a+c,0,0,0,0,1);return this},makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a=new p,b=new K;return function(c,
16266 d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),k=a.set(f[8],f[9],f[10]).length();0>this.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.");
16267 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;
16268 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,
16269 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},
16270 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,
16271 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+
16272 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,
16273 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;0<l?(c=.5/Math.sqrt(l+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&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=
16274 .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*=
16275 -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},
16276 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();
16277 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;
16278 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=
16279 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;
16280 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},
16281 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=
16282 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.");
16283 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]*
16284 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,
16285 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=
16286 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=
16287 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=
16288 -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-
16289 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=
16290 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-
16291 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=
16292 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=
16293 []);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)},
16294 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;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiply:function(a){return this.multiplyMatrices(this,
16295 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[3],f=c[6],g=c[1],h=c[4],k=c[7],l=c[2],q=c[5],c=c[8],n=d[0],m=d[3],r=d[6],p=d[1],v=d[4],w=d[7],x=d[2],z=d[5],d=d[8];b[0]=a*n+e*p+f*x;b[3]=a*m+e*v+f*z;b[6]=a*r+e*w+f*d;b[1]=g*n+h*p+k*x;b[4]=g*m+h*v+k*z;b[7]=g*r+h*w+k*d;b[2]=l*n+q*p+c*x;b[5]=l*m+q*v+c*z;b[8]=l*r+q*w+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;
16296 b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=a;return this},determinant:function(){var a=this.elements,b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],h=a[6],k=a[7],a=a[8];return b*f*a-b*g*k-c*e*a+c*g*h+d*e*k-d*f*h},getInverse:function(a,b){a&&a.isMatrix4&&console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");var c=a.elements;a=this.elements;var d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],q=c[7],c=c[8],n=c*h-k*q,m=k*l-c*g,r=q*g-h*l,p=d*n+e*m+f*r;if(0===p){if(!0===
16297 b)throw Error("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");console.warn("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/p;a[0]=n*b;a[1]=(f*q-c*e)*b;a[2]=(k*e-f*h)*b;a[3]=m*b;a[4]=(c*d-f*l)*b;a[5]=(f*g-k*d)*b;a[6]=r*b;a[7]=(e*l-q*d)*b;a[8]=(h*d-e*g)*b;return this},transpose:function(){var a=this.elements;var b=a[1];a[1]=a[3];a[3]=b;b=a[2];a[2]=a[6];a[6]=b;b=a[5];a[5]=a[7];a[7]=b;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},
16298 transposeIntoArray:function(a){var b=this.elements;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this},setUvTransform:function(a,b,c,d,e,f,g){var h=Math.cos(e);e=Math.sin(e);this.set(c*h,c*e,-c*(h*f+e*g)+f+a,-d*e,d*h,-d*(-e*f+h*g)+g+b,0,0,1)},scale:function(a,b){var c=this.elements;c[0]*=a;c[3]*=a;c[6]*=a;c[1]*=b;c[4]*=b;c[7]*=b;return this},rotate:function(a){var b=Math.cos(a);a=Math.sin(a);var c=this.elements,d=c[0],e=c[3],f=c[6],g=c[1],h=c[4],
16299 k=c[7];c[0]=b*d+a*g;c[3]=b*e+a*h;c[6]=b*f+a*k;c[1]=-a*d+b*g;c[4]=-a*e+b*h;c[7]=-a*f+b*k;return this},translate:function(a,b){var c=this.elements;c[0]+=a*c[2];c[3]+=a*c[5];c[6]+=a*c[8];c[1]+=b*c[2];c[4]+=b*c[5];c[7]+=b*c[8];return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;9>c;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=
16300 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=
16301 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;
16302 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};
16303 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=2048<h.width||2048<h.height?h.toDataURL("image/jpeg",.6):h.toDataURL("image/png");e[f]={uuid:g,
16304 url:h}}c.image=d.uuid}b||(a.textures[this.uuid]=c);return c},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.applyMatrix3(this.matrix);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);break;case 1001:a.x=0>a.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||1<a.y)switch(this.wrapT){case 1E3:a.y-=Math.floor(a.y);break;case 1001:a.y=0>a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%
16305 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;
16306 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."),
16307 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,
16308 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]*
16309 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+
16310 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;
16311 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,
16312 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);
16313 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},
16314 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+=
16315 (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,
16316 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=
16317 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=
16318 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,
16319 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,
16320 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,
16321 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,
16322 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,
16323 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,
16324 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&&
16325 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);1<d&&--d;return d<1/6?a+6*(c-a)*d:.5>d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=R.euclideanModulo(b,
16326 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,
16327 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,
16328 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<a.length&&(c=sg[a],void 0!==
16329 c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,b){void 0===b&&(b=2);this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);b=0<b?1/b:1;this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},convertGammaToLinear:function(){var a=
16330 this.r,b=this.g,c=this.b;this.r=a*a;this.g=b*b;this.b=c*c;return this},convertLinearToGamma:function(){this.r=Math.sqrt(this.r);this.g=Math.sqrt(this.g);this.b=Math.sqrt(this.b);return this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(a){a=a||{h:0,s:0,l:0};var b=this.r,c=this.g,d=this.b,e=Math.max(b,c,d),f=Math.min(b,c,d),g,h=(f+e)/2;if(f===e)f=g=0;else{var k=e-f,f=.5>=h?k/(e+f):
16331 k/(2-e-f);switch(e){case b:g=(c-d)/k+(c<d?6:0);break;case c:g=(d-b)/k+2;break;case d:g=(b-c)/k+4}g/=6}a.h=g;a.s=f;a.l=h;return a},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();d.h+=a;d.s+=b;d.l+=c;this.setHSL(d.h,d.s,d.l);return this},add:function(a){this.r+=a.r;this.g+=a.g;this.b+=a.b;return this},addColors:function(a,b){this.r=a.r+b.r;this.g=a.g+b.g;this.b=a.b+b.b;return this},addScalar:function(a){this.r+=
16332 a;this.g+=a;this.b+=a;return this},sub:function(a){this.r=Math.max(0,this.r-a.r);this.g=Math.max(0,this.g-a.g);this.b=Math.max(0,this.b-a.b);return this},multiply:function(a){this.r*=a.r;this.g*=a.g;this.b*=a.b;return this},multiplyScalar:function(a){this.r*=a;this.g*=a;this.b*=a;return this},lerp:function(a,b){this.r+=(a.r-this.r)*b;this.g+=(a.g-this.g)*b;this.b+=(a.b-this.b)*b;return this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a,b){void 0===b&&(b=
16333 0);this.r=a[b];this.g=a[b+1];this.b=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.r;a[b+1]=this.g;a[b+2]=this.b;return a},toJSON:function(){return this.getHex()}});var E={common:{diffuse:{value:new H(15658734)},opacity:{value:1},map:{value:null},uvTransform:{value:new ra},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},
16334 aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new C(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:2.5E-4},fogNear:{value:1},
16335 fogFar:{value:2E3},fogColor:{value:new H(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},
16336 pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new H(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},uvTransform:{value:new ra}}},
16337 Ea={merge:function(a){for(var b={},c=0;c<a.length;c++){var d=this.clone(a[c]),e;for(e in d)b[e]=d[e]}return b},clone:function(a){var b={},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},W={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",
16338 alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n",
16339 aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 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",
16340 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",
16341 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",
16342 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",
16343 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",
16344 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",
16345 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",
16346 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",
16347 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",
16348 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",
16349 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",
16350 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",
16351 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",
16352 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",
16353 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",
16354 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",
16355 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",
16356 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",
16357 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",
16358 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",
16359 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",
16360 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",
16361 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",
16362 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",
16363 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",
16364 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",
16365 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",
16366 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",
16367 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",
16368 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",
16369 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",
16370 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",
16371 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",
16372 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",
16373 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",
16374 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",
16375 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",
16376 cube_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\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",
16377 depth_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n",
16378 distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n",
16379 distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n",
16380 equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\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 <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",
16381 linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16382 linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n",
16383 meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\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 <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16384 meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n",
16385 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 <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\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 <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16386 meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16387 meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16388 meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16389 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 <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16390 meshphysical_vert:"#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16391 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 <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
16392 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 <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",
16393 points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16394 points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\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 <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16395 shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}\n",shadow_vert:"#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n"},
16396 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,
16397 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,
16398 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},
16399 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,
16400 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;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new C;return function(b,c){c=a.copy(c).multiplyScalar(.5);
16401 this.min.copy(b).sub(c);this.max.copy(b).add(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=
16402 a||new C;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.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<=
16403 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.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.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);
16404 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: '"+
16405 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=
16406 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);
16407 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&&
16408 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);
16409 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&&
16410 (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);
16411 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);0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&(d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&
16412 (d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);!0===this.morphTargets&&(d.morphTargets=!0);!0===this.skinning&&(d.skinning=!0);!1===this.visible&&(d.visible=!1);"{}"!==JSON.stringify(this.userData)&&(d.userData=this.userData);c&&(c=b(a.textures),a=b(a.images),0<c.length&&(d.textures=c),0<a.length&&(d.images=a));return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.fog=a.fog;
16413 this.lights=a.lights;this.blending=a.blending;this.side=a.side;this.flatShading=a.flatShading;this.vertexColors=a.vertexColors;this.opacity=a.opacity;this.transparent=a.transparent;this.blendSrc=a.blendSrc;this.blendDst=a.blendDst;this.blendEquation=a.blendEquation;this.blendSrcAlpha=a.blendSrcAlpha;this.blendDstAlpha=a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;this.depthFunc=a.depthFunc;this.depthTest=a.depthTest;this.depthWrite=a.depthWrite;this.colorWrite=a.colorWrite;this.precision=
16414 a.precision;this.polygonOffset=a.polygonOffset;this.polygonOffsetFactor=a.polygonOffsetFactor;this.polygonOffsetUnits=a.polygonOffsetUnits;this.dithering=a.dithering;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=a.visible;this.userData=JSON.parse(JSON.stringify(a.userData));this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;a=a.clippingPlanes;var b=null;if(null!==a)for(var c=a.length,b=Array(c),d=0;d!==c;++d)b[d]=
16415 a[d].clone();this.clippingPlanes=b;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Wa.prototype=Object.create(Q.prototype);Wa.prototype.constructor=Wa;Wa.prototype.isMeshDepthMaterial=!0;Wa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.depthPacking=a.depthPacking;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=
16416 a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};Xa.prototype=Object.create(Q.prototype);Xa.prototype.constructor=Xa;Xa.prototype.isMeshDistanceMaterial=!0;Xa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.referencePosition.copy(a.referencePosition);this.nearDistance=a.nearDistance;this.farDistance=a.farDistance;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=
16417 a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;return this};Object.assign(Oa.prototype,{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var l=a[h],q=a[h+1],n=a[h+2];l<b&&(b=l);q<c&&(c=q);n<d&&(d=n);l>e&&(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=
16418 Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var l=a.getX(h),q=a.getY(h),n=a.getZ(h);l<b&&(b=l);q<c&&(c=q);n<d&&(d=n);l>e&&(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;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new p;return function(b,c){c=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(c);this.max.copy(b).add(c);
16419 return this}}(),setFromObject:function(a){this.makeEmpty();return this.expandByObject(a)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new p;return this.isEmpty()?a.set(0,0,0):
16420 a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new p;return this.isEmpty()?a.set(0,0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},expandByObject:function(){function a(a){var f=a.geometry;if(void 0!==f)if(f.isGeometry)for(f=f.vertices,c=0,d=f.length;c<d;c++)e.copy(f[c]),
16421 e.applyMatrix4(a.matrixWorld),b.expandByPoint(e);else if(f.isBufferGeometry&&(f=f.attributes.position,void 0!==f))for(c=0,d=f.count;c<d;c++)e.fromBufferAttribute(f,c).applyMatrix4(a.matrixWorld),b.expandByPoint(e)}var b,c,d,e=new p;return function(c){b=this;c.updateMatrixWorld(!0);c.traverse(a);return this}}(),containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y||a.z<this.min.z||a.z>this.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=
16422 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.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new p;return function(b){this.clampPoint(b.center,
16423 a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){if(0<a.normal.x){var b=a.normal.x*this.min.x;var c=a.normal.x*this.max.x}else b=a.normal.x*this.max.x,c=a.normal.x*this.min.x;0<a.normal.y?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y);0<a.normal.z?(b+=a.normal.z*this.min.z,c+=a.normal.z*this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z);return b<=a.constant&&c>=a.constant},clampPoint:function(a,
16424 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=
16425 [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);
16426 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<f;e++)c=Math.max(c,
16427 d.distanceToSquared(b[e]));this.radius=Math.sqrt(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.center.copy(a.center);this.radius=a.radius;return this},empty:function(){return 0>=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)<=
16428 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);
16429 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=
16430 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)+
16431 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||1<e))return c.copy(d).multiplyScalar(e).add(b.start)}}(),intersectsLine:function(a){var b=
16432 this.distanceToPoint(a.start);a=this.distanceToPoint(a.end);return 0>b&&0<a||0>a&&0<b},intersectsBox:function(a){return a.intersectsPlane(this)},intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new p).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new p,b=new ra;return function(c,d){d=d||b.getNormalMatrix(c);c=this.coplanarPoint(a).applyMatrix4(c);d=this.normal.applyMatrix3(d).normalize();this.constant=-c.dot(d);return this}}(),
16433 translate:function(a){this.constant-=a.dot(this.normal);return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}});Object.assign(ld.prototype,{set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,
16434 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=
16435 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)<a)return!1;return!0},intersectsBox:function(){var a=new p,b=
16436 new p;return function(c){for(var d=this.planes,e=0;6>e;e++){var f=d[e];a.x=0<f.normal.x?c.min.x:c.max.x;b.x=0<f.normal.x?c.max.x:c.min.x;a.y=0<f.normal.y?c.min.y:c.max.y;b.y=0<f.normal.y?c.max.y:c.min.y;a.z=0<f.normal.z?c.min.z:c.max.z;b.z=0<f.normal.z?c.max.z:c.min.z;var g=f.distanceToPoint(a),f=f.distanceToPoint(b);if(0>g&&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(" ");
16437 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=
16438 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=
16439 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"===
16440 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);
16441 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===
16442 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<<a|0},enable:function(a){this.mask=this.mask|1<<a|0},toggle:function(a){this.mask^=1<<a|0},disable:function(a){this.mask&=~(1<<a|0)},test:function(a){return 0!==(this.mask&a.mask)}});
16443 var Nf=0;A.DefaultUp=new p(0,1,0);A.DefaultMatrixAutoUpdate=!0;Object.assign(A.prototype,ja.prototype,{isObject3D:!0,onBeforeRender:function(){},onAfterRender:function(){},applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},applyQuaternion:function(a){this.quaternion.premultiply(a);return this},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,
16444 !0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new Z;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateOnWorldAxis:function(){var a=new Z;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.premultiply(a);return this}}(),rotateX:function(){var a=new p(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=
16445 new p(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new p(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new p;return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new p(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new p(0,1,0);return function(b){return this.translateOnAxis(a,
16446 b)}}(),translateZ:function(){var a=new p(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=new K;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new K,b=new p;return function(c,d,e){c.isVector3?b.copy(c):b.set(c,d,e);this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),
16447 add:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.add(arguments[b]);return this}if(a===this)return console.error("THREE.Object3D.add: object can't be added as a child of itself.",a),this;a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),this.children.push(a)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",a);return this},remove:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.remove(arguments[b]);
16448 return this}b=this.children.indexOf(a);-1!==b&&(a.parent=null,a.dispatchEvent({type:"removed"}),this.children.splice(b,1));return this},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",a)},getObjectByProperty:function(a,b){if(this[a]===b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c].getObjectByProperty(a,b);if(void 0!==e)return e}},getWorldPosition:function(a){a=a||new p;this.updateMatrixWorld(!0);
16449 return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new p,b=new p;return function(c){c=c||new Z;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new Z;return function(b){b=b||new Ya;this.getWorldQuaternion(a);return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new p,b=new Z;return function(c){c=c||new p;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),
16450 getWorldDirection:function(){var a=new Z;return function(b){b=b||new p;this.getWorldQuaternion(a);return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverseVisible(a)}},traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,
16451 this.quaternion,this.scale);this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&this.updateMatrix();if(this.matrixWorldNeedsUpdate||a)null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0;for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].updateMatrixWorld(a)},toJSON:function(a){function b(b,c){void 0===b[c.uuid]&&(b[c.uuid]=c.toJSON(a));return c.uuid}function c(a){var b=
16452 [],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var d=void 0===a||"string"===typeof a,e={};d&&(a={geometries:{},materials:{},textures:{},images:{}},e.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});var f={};f.uuid=this.uuid;f.type=this.type;""!==this.name&&(f.name=this.name);!0===this.castShadow&&(f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);f.matrix=
16453 this.matrix.toArray();void 0!==this.geometry&&(f.geometry=b(a.geometries,this.geometry));if(void 0!==this.material)if(Array.isArray(this.material)){for(var g=[],h=0,k=this.material.length;h<k;h++)g.push(b(a.materials,this.material[h]));f.material=g}else f.material=b(a.materials,this.material);if(0<this.children.length)for(f.children=[],h=0;h<this.children.length;h++)f.children.push(this.children[h].toJSON(a).object);d&&(d=c(a.geometries),g=c(a.materials),h=c(a.textures),k=c(a.images),0<d.length&&
16454 (e.geometries=d),0<g.length&&(e.materials=g),0<h.length&&(e.textures=h),0<k.length&&(e.images=k));e.object=f;return e},clone:function(a){return(new this.constructor).copy(this,a)},copy:function(a,b){void 0===b&&(b=!0);this.name=a.name;this.up.copy(a.up);this.position.copy(a.position);this.quaternion.copy(a.quaternion);this.scale.copy(a.scale);this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;
16455 this.layers.mask=a.layers.mask;this.visible=a.visible;this.castShadow=a.castShadow;this.receiveShadow=a.receiveShadow;this.frustumCulled=a.frustumCulled;this.renderOrder=a.renderOrder;this.userData=JSON.parse(JSON.stringify(a.userData));if(!0===b)for(b=0;b<a.children.length;b++)this.add(a.children[b].clone());return this}});La.prototype=Object.assign(Object.create(A.prototype),{constructor:La,isCamera:!0,copy:function(a,b){A.prototype.copy.call(this,a,b);this.matrixWorldInverse.copy(a.matrixWorldInverse);
16456 this.projectionMatrix.copy(a.projectionMatrix);return this},getWorldDirection:function(){var a=new Z;return function(b){b=b||new p;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){A.prototype.updateMatrixWorld.call(this,a);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});Kb.prototype=Object.assign(Object.create(La.prototype),{constructor:Kb,isOrthographicCamera:!0,copy:function(a,b){La.prototype.copy.call(this,
16457 a,b);this.left=a.left;this.right=a.right;this.top=a.top;this.bottom=a.bottom;this.near=a.near;this.far=a.far;this.zoom=a.zoom;this.view=null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,f){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},
16458 clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),c=(this.right+this.left)/2,d=(this.top+this.bottom)/2,e=c-a,c=c+a,a=d+b,b=d-b;if(null!==this.view&&this.view.enabled)var c=this.zoom/(this.view.width/this.view.fullWidth),b=this.zoom/(this.view.height/this.view.fullHeight),f=(this.right-this.left)/this.view.width,d=(this.top-this.bottom)/
16459 this.view.height,e=e+this.view.offsetX/c*f,c=e+this.view.width/c*f,a=a-this.view.offsetY/b*d,b=a-this.view.height/b*d;this.projectionMatrix.makeOrthographic(e,c,a,b,this.near,this.far)},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.zoom=this.zoom;a.object.left=this.left;a.object.right=this.right;a.object.top=this.top;a.object.bottom=this.bottom;a.object.near=this.near;a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});Object.assign(Pa.prototype,
16460 {clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});var Of=0;Object.assign(N.prototype,ja.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=(new ra).getNormalMatrix(a),
16461 c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();this.normalsNeedUpdate=this.verticesNeedUpdate=!0;return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);this.applyMatrix(a);
16462 return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new A;return function(b){a.lookAt(b);
16463 a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[q[a].clone(),q[b].clone(),q[d].clone()]:[],t=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Pa(a,b,d,f,t,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([n[a].clone(),n[b].clone(),n[d].clone()]);void 0!==l&&c.faceVertexUvs[1].push([m[a].clone(),m[b].clone(),m[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,
16464 g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,l=void 0!==e.uv2?e.uv2.array:void 0;void 0!==l&&(this.faceVertexUvs[1]=[]);for(var q=[],n=[],m=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new p(f[e],f[e+1],f[e+2])),void 0!==g&&q.push(new p(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new H(h[e],h[e+1],h[e+2])),void 0!==k&&n.push(new C(k[r],k[r+1])),void 0!==l&&m.push(new C(l[r],l[r+1]));var u=a.groups;if(0<u.length)for(e=0;e<u.length;e++)for(var f=
16465 u[e],v=f.start,w=f.count,r=v,v=v+w;r<v;r+=3)void 0!==d?b(d[r],d[r+1],d[r+2],f.materialIndex):b(r,r+1,r+2,f.materialIndex);else if(void 0!==d)for(e=0;e<d.length;e+=3)b(d[e],d[e+1],d[e+2]);else for(e=0;e<f.length/3;e+=3)b(e,e+1,e+2);this.computeFaceNormals();null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());return this},center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,
16466 a.y,a.z);return a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,b=0===b?1:1/b,c=new K;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new p,b=new p,c=0,d=this.faces.length;c<d;c++){var e=this.faces[c],f=this.vertices[e.a],g=this.vertices[e.b];a.subVectors(this.vertices[e.c],g);b.subVectors(f,g);a.cross(b);a.normalize();e.normal.copy(a)}},computeVertexNormals:function(a){void 0===
16467 a&&(a=!0);var b;var c=Array(this.vertices.length);var d=0;for(b=this.vertices.length;d<b;d++)c[d]=new p;if(a){var e=new p,f=new p;a=0;for(d=this.faces.length;a<d;a++){b=this.faces[a];var g=this.vertices[b.a];var h=this.vertices[b.b];var k=this.vertices[b.c];e.subVectors(k,h);f.subVectors(g,h);e.cross(f);c[b.a].add(e);c[b.b].add(e);c[b.c].add(e)}}else for(this.computeFaceNormals(),a=0,d=this.faces.length;a<d;a++)b=this.faces[a],c[b.a].add(b.normal),c[b.b].add(b.normal),c[b.c].add(b.normal);d=0;for(b=
16468 this.vertices.length;d<b;d++)c[d].normalize();a=0;for(d=this.faces.length;a<d;a++)b=this.faces[a],g=b.vertexNormals,3===g.length?(g[0].copy(c[b.a]),g[1].copy(c[b.b]),g[2].copy(c[b.c])):(g[0]=c[b.a].clone(),g[1]=c[b.b].clone(),g[2]=c[b.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a;this.computeFaceNormals();var b=0;for(a=this.faces.length;b<a;b++){var c=this.faces[b];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),
16469 d[2].copy(c.normal)):(d[0]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b;var c=0;for(b=this.faces.length;c<b;c++){var d=this.faces[c];d.__originalFaceNormal?d.__originalFaceNormal.copy(d.normal):d.__originalFaceNormal=d.normal.clone();d.__originalVertexNormals||(d.__originalVertexNormals=[]);var e=0;for(a=d.vertexNormals.length;e<a;e++)d.__originalVertexNormals[e]?d.__originalVertexNormals[e].copy(d.vertexNormals[e]):
16470 d.__originalVertexNormals[e]=d.vertexNormals[e].clone()}var f=new N;f.faces=this.faces;e=0;for(a=this.morphTargets.length;e<a;e++){if(!this.morphNormals[e]){this.morphNormals[e]={};this.morphNormals[e].faceNormals=[];this.morphNormals[e].vertexNormals=[];d=this.morphNormals[e].faceNormals;var g=this.morphNormals[e].vertexNormals;c=0;for(b=this.faces.length;c<b;c++){var h=new p;var k={a:new p,b:new p,c:new p};d.push(h);g.push(k)}}g=this.morphNormals[e];f.vertices=this.morphTargets[e].vertices;f.computeFaceNormals();
16471 f.computeVertexNormals();c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(d.normal),k.a.copy(d.vertexNormals[0]),k.b.copy(d.vertexNormals[1]),k.c.copy(d.vertexNormals[2])}c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],d.normal=d.__originalFaceNormal,d.vertexNormals=d.__originalVertexNormals},computeLineDistances:function(){for(var a=0,b=this.vertices,c=0,d=b.length;c<d;c++)0<c&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===
16472 this.boundingBox&&(this.boundingBox=new Oa);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Da);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(a&&a.isGeometry){var d,e=this.vertices.length,f=this.vertices,g=a.vertices,h=this.faces,k=a.faces,l=this.faceVertexUvs[0],q=a.faceVertexUvs[0],n=this.colors,m=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new ra).getNormalMatrix(b));a=0;for(var r=g.length;a<
16473 r;a++){var p=g[a].clone();void 0!==b&&p.applyMatrix4(b);f.push(p)}a=0;for(r=m.length;a<r;a++)n.push(m[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],v=g.vertexNormals,m=g.vertexColors,n=new Pa(g.a+e,g.b+e,g.c+e);n.normal.copy(g.normal);void 0!==d&&n.normal.applyMatrix3(d).normalize();b=0;for(f=v.length;b<f;b++)p=v[b].clone(),void 0!==d&&p.applyMatrix3(d).normalize(),n.vertexNormals.push(p);n.color.copy(g.color);b=0;for(f=m.length;b<f;b++)p=m[b],n.vertexColors.push(p.clone());n.materialIndex=g.materialIndex+
16474 c;h.push(n)}a=0;for(r=q.length;a<r;a++)if(c=q[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());l.push(d)}}else console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a)},mergeMesh:function(a){a&&a.isMesh?(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix)):console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a)},mergeVertices:function(){var a={},b=[],c=[],d=Math.pow(10,4),e;var f=0;for(e=this.vertices.length;f<
16475 e;f++){var g=this.vertices[f];g=Math.round(g.x*d)+"_"+Math.round(g.y*d)+"_"+Math.round(g.z*d);void 0===a[g]?(a[g]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[g]]}a=[];f=0;for(e=this.faces.length;f<e;f++)for(d=this.faces[f],d.a=c[d.a],d.b=c[d.b],d.c=c[d.c],d=[d.a,d.b,d.c],g=0;3>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;c<e;c++)this.faceVertexUvs[c].splice(d,1);f=this.vertices.length-b.length;this.vertices=
16476 b;return f},setFromPoints:function(a){this.vertices=[];for(var b=0,c=a.length;b<c;b++){var d=a[b];this.vertices.push(new p(d.x,d.y,d.z||0))}return this},sortFacesByMaterialIndex:function(){for(var a=this.faces,b=a.length,c=0;c<b;c++)a[c]._id=c;a.sort(function(a,b){return a.materialIndex-b.materialIndex});var d=this.faceVertexUvs[0],e=this.faceVertexUvs[1],f,g;d&&d.length===b&&(f=[]);e&&e.length===b&&(g=[]);for(c=0;c<b;c++){var h=a[c]._id;f&&f.push(d[h]);g&&g.push(e[h])}f&&(this.faceVertexUvs[0]=f);
16477 g&&(this.faceVertexUvs[1]=g)},toJSON:function(){function a(a,b,c){return c?a|1<<b:a&~(1<<b)}function b(a){var b=a.x.toString()+a.y.toString()+a.z.toString();if(void 0!==l[b])return l[b];l[b]=k.length/3;k.push(a.x,a.y,a.z);return l[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==n[b])return n[b];n[b]=q.length;q.push(a.getHex());return n[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==p[b])return p[b];p[b]=m.length/2;m.push(a.x,a.y);return p[b]}var e=
16478 {metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==this.parameters){var f=this.parameters,g;for(g in f)void 0!==f[g]&&(e[g]=f[g]);return e}f=[];for(g=0;g<this.vertices.length;g++){var h=this.vertices[g];f.push(h.x,h.y,h.z)}var h=[],k=[],l={},q=[],n={},m=[],p={};for(g=0;g<this.faces.length;g++){var u=this.faces[g],v=void 0!==this.faceVertexUvs[0][g],w=0<u.normal.length(),x=0<u.vertexNormals.length,z=
16479 1!==u.color.r||1!==u.color.g||1!==u.color.b,I=0<u.vertexColors.length,B=0,B=a(B,0,0),B=a(B,1,!0),B=a(B,2,!1),B=a(B,3,v),B=a(B,4,w),B=a(B,5,x),B=a(B,6,z),B=a(B,7,I);h.push(B);h.push(u.a,u.b,u.c);h.push(u.materialIndex);v&&(v=this.faceVertexUvs[0][g],h.push(d(v[0]),d(v[1]),d(v[2])));w&&h.push(b(u.normal));x&&(w=u.vertexNormals,h.push(b(w[0]),b(w[1]),b(w[2])));z&&h.push(c(u.color));I&&(u=u.vertexColors,h.push(c(u[0]),c(u[1]),c(u[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<q.length&&(e.data.colors=
16480 q);0<m.length&&(e.data.uvs=[m]);e.data.faces=h;return e},clone:function(){return(new N).copy(this)},copy:function(a){var b,c,d;this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var e=a.vertices;var f=0;for(b=e.length;f<b;f++)this.vertices.push(e[f].clone());e=a.colors;f=0;for(b=e.length;f<b;f++)this.colors.push(e[f].clone());
16481 e=a.faces;f=0;for(b=e.length;f<b;f++)this.faces.push(e[f].clone());f=0;for(b=a.faceVertexUvs.length;f<b;f++){var g=a.faceVertexUvs[f];void 0===this.faceVertexUvs[f]&&(this.faceVertexUvs[f]=[]);e=0;for(c=g.length;e<c;e++){var h=g[e],k=[];var l=0;for(d=h.length;l<d;l++)k.push(h[l].clone());this.faceVertexUvs[f].push(k)}}l=a.morphTargets;f=0;for(b=l.length;f<b;f++){d={};d.name=l[f].name;if(void 0!==l[f].vertices)for(d.vertices=[],e=0,c=l[f].vertices.length;e<c;e++)d.vertices.push(l[f].vertices[e].clone());
16482 if(void 0!==l[f].normals)for(d.normals=[],e=0,c=l[f].normals.length;e<c;e++)d.normals.push(l[f].normals[e].clone());this.morphTargets.push(d)}l=a.morphNormals;f=0;for(b=l.length;f<b;f++){d={};if(void 0!==l[f].vertexNormals)for(d.vertexNormals=[],e=0,c=l[f].vertexNormals.length;e<c;e++)g=l[f].vertexNormals[e],h={},h.a=g.a.clone(),h.b=g.b.clone(),h.c=g.c.clone(),d.vertexNormals.push(h);if(void 0!==l[f].faceNormals)for(d.faceNormals=[],e=0,c=l[f].faceNormals.length;e<c;e++)d.faceNormals.push(l[f].faceNormals[e].clone());
16483 this.morphNormals.push(d)}e=a.skinWeights;f=0;for(b=e.length;f<b;f++)this.skinWeights.push(e[f].clone());e=a.skinIndices;f=0;for(b=e.length;f<b;f++)this.skinIndices.push(e[f].clone());e=a.lineDistances;f=0;for(b=e.length;f<b;f++)this.lineDistances.push(e[f]);f=a.boundingBox;null!==f&&(this.boundingBox=f.clone());f=a.boundingSphere;null!==f&&(this.boundingSphere=f.clone());this.elementsNeedUpdate=a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=
16484 a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.defineProperty(P.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(P.prototype,{isBufferAttribute:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==
16485 a?a.length/this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.itemSize=a.itemSize;this.count=a.count;this.normalized=a.normalized;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.itemSize;c*=b.itemSize;for(var d=0,e=this.itemSize;d<e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=
16486 0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new H);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a;b[c++]=f.b;b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",d),f=new C);
16487 b[c++]=f.x;b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new p);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new da);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z;
16488 b[c++]=f.w}return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+3]},
16489 setW:function(a,b){this.array[a*this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;this.array[a+3]=e;return this},onUpload:function(a){this.onUploadCallback=a;return this},clone:function(){return(new this.constructor(this.array,
16490 this.itemSize)).copy(this)}});uc.prototype=Object.create(P.prototype);uc.prototype.constructor=uc;vc.prototype=Object.create(P.prototype);vc.prototype.constructor=vc;wc.prototype=Object.create(P.prototype);wc.prototype.constructor=wc;xc.prototype=Object.create(P.prototype);xc.prototype.constructor=xc;hb.prototype=Object.create(P.prototype);hb.prototype.constructor=hb;yc.prototype=Object.create(P.prototype);yc.prototype.constructor=yc;ib.prototype=Object.create(P.prototype);ib.prototype.constructor=
16491 ib;y.prototype=Object.create(P.prototype);y.prototype.constructor=y;zc.prototype=Object.create(P.prototype);zc.prototype.constructor=zc;Object.assign(Je.prototype,{computeGroups:function(a){var b=[],c=void 0;a=a.faces;for(var d=0;d<a.length;d++){var e=a[d];if(e.materialIndex!==c){c=e.materialIndex;void 0!==f&&(f.count=3*d-f.start,b.push(f));var f={start:3*d,materialIndex:c}}}void 0!==f&&(f.count=3*d-f.start,b.push(f));this.groups=b},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,
16492 e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length;if(0<h){var k=[];for(var l=0;l<h;l++)k[l]=[];this.morphTargets.position=k}var q=a.morphNormals,n=q.length;if(0<n){var m=[];for(l=0;l<n;l++)m[l]=[];this.morphTargets.normal=m}for(var p=a.skinIndices,u=a.skinWeights,v=p.length===c.length,w=u.length===c.length,l=0;l<b.length;l++){var x=b[l];this.vertices.push(c[x.a],c[x.b],c[x.c]);var z=x.vertexNormals;3===z.length?this.normals.push(z[0],z[1],z[2]):(z=x.normal,this.normals.push(z,
16493 z,z));z=x.vertexColors;3===z.length?this.colors.push(z[0],z[1],z[2]):(z=x.color,this.colors.push(z,z,z));!0===e&&(z=d[0][l],void 0!==z?this.uvs.push(z[0],z[1],z[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",l),this.uvs.push(new C,new C,new C)));!0===f&&(z=d[1][l],void 0!==z?this.uvs2.push(z[0],z[1],z[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",l),this.uvs2.push(new C,new C,new C)));for(z=0;z<h;z++){var I=g[z].vertices;k[z].push(I[x.a],
16494 I[x.b],I[x.c])}for(z=0;z<n;z++)I=q[z].vertexNormals[l],m[z].push(I.a,I.b,I.c);v&&this.skinIndices.push(p[x.a],p[x.b],p[x.c]);w&&this.skinWeights.push(u[x.a],u[x.b],u[x.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this}});var Pf=1;Object.assign(D.prototype,ja.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},
16495 setIndex:function(a){Array.isArray(a)?this.index=new (65535<Qd(a)?ib:hb)(a,1):this.index=a},addAttribute:function(a,b,c){if(b&&b.isBufferAttribute||b&&b.isInterleavedBufferAttribute)if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(b);else return this.attributes[a]=b,this;else console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(a,new P(b,c))},getAttribute:function(a){return this.attributes[a]},
16496 removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a;this.drawRange.count=b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToBufferAttribute(b),b.needsUpdate=!0);b=this.attributes.normal;void 0!==b&&((new ra).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==
16497 this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,
16498 c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new A;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new y(3*b.vertices.length,3);var c=new y(3*b.colors.length,
16499 3);this.addAttribute("position",a.copyVector3sArray(b.vertices));this.addAttribute("color",c.copyColorsArray(b.colors));b.lineDistances&&b.lineDistances.length===b.vertices.length&&(a=new y(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},setFromPoints:function(a){for(var b=
16500 [],c=0,d=a.length;c<d;c++){var e=a[c];b.push(e.x,e.y,e.z||0)}this.addAttribute("position",new y(b,3));return this},updateFromObject:function(a){var b=a.geometry;if(a.isMesh){var c=b.__directGeometry;!0===b.elementsNeedUpdate&&(c=void 0,b.elementsNeedUpdate=!1);if(void 0===c)return this.fromGeometry(b);c.verticesNeedUpdate=b.verticesNeedUpdate;c.normalsNeedUpdate=b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=
16501 !1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),c.needsUpdate=!0),b.normalsNeedUpdate=!1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),b.colorsNeedUpdate=
16502 !1);b.uvsNeedUpdate&&(c=this.attributes.uv,void 0!==c&&(c.copyVector2sArray(b.uvs),c.needsUpdate=!0),b.uvsNeedUpdate=!1);b.lineDistancesNeedUpdate&&(c=this.attributes.lineDistance,void 0!==c&&(c.copyArray(b.lineDistances),c.needsUpdate=!0),b.lineDistancesNeedUpdate=!1);b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1);return this},fromGeometry:function(a){a.__directGeometry=(new Je).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=
16503 new Float32Array(3*a.vertices.length);this.addAttribute("position",(new P(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new P(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new P(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new P(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=
16504 new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new P(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<Qd(a.indices)?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new P(b,1)).copyIndicesArray(a.indices)));this.groups=a.groups;for(var c in a.morphTargets){for(var b=[],d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new y(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new y(4*a.skinIndices.length,
16505 4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new y(4*a.skinWeights.length,4),this.addAttribute("skinWeight",c.copyVector4sArray(a.skinWeights)));null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());return this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Oa);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):
16506 this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var a=new Oa,b=new p;return function(){null===this.boundingSphere&&(this.boundingSphere=new Da);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);
16507 a.getCenter(d);for(var e=0,f=0,g=c.count;f<g;f++)b.x=c.getX(f),b.y=c.getY(f),b.z=c.getZ(f),e=Math.max(e,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(e);isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;
16508 if(void 0===b.normal)this.addAttribute("normal",new P(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;var e=b.normal.array,h=new p,k=new p,l=new p,q=new p,n=new p;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var m=0,r=c.length;m<r;++m){f=c[m];g=f.start;var u=f.count;f=g;for(g+=u;f<g;f+=3){u=3*a[f+0];var v=3*a[f+1];var w=3*a[f+2];h.fromArray(d,u);k.fromArray(d,v);l.fromArray(d,w);q.subVectors(l,k);n.subVectors(h,k);q.cross(n);e[u]+=q.x;e[u+
16509 1]+=q.y;e[u+2]+=q.z;e[v]+=q.x;e[v+1]+=q.y;e[v+2]+=q.z;e[w]+=q.x;e[w+1]+=q.y;e[w+2]+=q.z}}}else for(f=0,g=d.length;f<g;f+=9)h.fromArray(d,f),k.fromArray(d,f+3),l.fromArray(d,f+6),q.subVectors(l,k),n.subVectors(h,k),q.cross(n),e[f]=q.x,e[f+1]=q.y,e[f+2]=q.z,e[f+3]=q.x,e[f+4]=q.y,e[f+5]=q.z,e[f+6]=q.x,e[f+7]=q.y,e[f+8]=q.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(a&&a.isBufferGeometry){void 0===b&&(b=0);var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d])for(var e=
16510 c[d].array,f=a.attributes[d],g=f.array,h=0,f=f.itemSize*b;h<g.length;h++,f++)e[f]=g[h];return this}console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",a)},normalizeNormals:function(){var a=new p;return function(){for(var b=this.attributes.normal,c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.normalize(),b.setXYZ(c,a.x,a.y,a.z)}}(),toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),
16511 this;var a=new D,b=this.index.array,c=this.attributes,d;for(d in c){for(var e=c[d],f=e.array,e=e.itemSize,g=new f.constructor(b.length*e),h,k=0,l=0,q=b.length;l<q;l++){h=b[l]*e;for(var n=0;n<e;n++)g[k++]=f[h++]}a.addAttribute(d,new P(g,e))}return a},toJSON:function(){var a={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&(a.name=this.name);if(void 0!==this.parameters){var b=this.parameters;for(var c in b)void 0!==b[c]&&
16512 (a[c]=b[c]);return a}a.data={attributes:{}};var d=this.index;null!==d&&(b=Array.prototype.slice.call(d.array),a.data.index={type:d.array.constructor.name,array:b});d=this.attributes;for(c in d){var e=d[c];b=Array.prototype.slice.call(e.array);a.data.attributes[c]={itemSize:e.itemSize,type:e.array.constructor.name,array:b,normalized:e.normalized}}c=this.groups;0<c.length&&(a.data.groups=JSON.parse(JSON.stringify(c)));c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),
16513 radius:c.radius});return a},clone:function(){return(new D).copy(this)},copy:function(a){var b;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var c=a.index;null!==c&&this.setIndex(c.clone());c=a.attributes;for(g in c)this.addAttribute(g,c[g].clone());var d=a.morphAttributes;for(g in d){var e=[],f=d[g];c=0;for(b=f.length;c<b;c++)e.push(f[c].clone());this.morphAttributes[g]=e}var g=a.groups;c=0;for(b=g.length;c<b;c++)d=
16514 g[c],this.addGroup(d.start,d.count,d.materialIndex);g=a.boundingBox;null!==g&&(this.boundingBox=g.clone());g=a.boundingSphere;null!==g&&(this.boundingSphere=g.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Lb.prototype=Object.create(N.prototype);Lb.prototype.constructor=Lb;jb.prototype=Object.create(D.prototype);jb.prototype.constructor=jb;Ac.prototype=Object.create(N.prototype);Ac.prototype.constructor=
16515 Ac;kb.prototype=Object.create(D.prototype);kb.prototype.constructor=kb;va.prototype=Object.create(Q.prototype);va.prototype.constructor=va;va.prototype.isMeshBasicMaterial=!0;va.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.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=
16516 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;return this};oa.prototype=Object.create(Q.prototype);oa.prototype.constructor=oa;oa.prototype.isShaderMaterial=!0;oa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;
16517 this.uniforms=Ea.clone(a.uniforms);this.defines=a.defines;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.lights=a.lights;this.clipping=a.clipping;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;this.extensions=a.extensions;return this};oa.prototype.toJSON=function(a){a=Q.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Object.assign(lb.prototype,
16518 {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 p).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 p;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,
16519 b){b=b||new p;b.subVectors(a,this.origin);a=b.dot(this.direction);return 0>a?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=
16520 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<m){d=k*q-l;e=k*l-q;var p=h*m;0<=d?e>=-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=0<d?-h:Math.min(Math.max(-h,
16521 -q),h),k=-d*d+e*(e+2*q)+n):e<=p?(d=0,e=Math.min(Math.max(-h,-q),h),k=e*(e+2*q)+n):(d=Math.max(0,-(k*h+l)),e=0<d?h:Math.min(Math.max(-h,-q),h),k=-d*d+e*(e+2*q)+n)}else e=0<k?-h:h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n;f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new p;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d;b=b.radius*b.radius;if(e>b)return null;
16522 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);
16523 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(d<c||c!==c)c=d;0<=e?(h=(a.min.z-f.z)*e,a=(a.max.z-f.z)*e):(h=(a.max.z-f.z)*e,a=(a.min.z-f.z)*e);if(g>a||h>c)return null;
16524 if(h>g||g!==g)g=h;if(a<c||c!==c)c=a;return 0>c?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(0<f){if(h)return null;h=1}else if(0>f)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;
16525 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);
16526 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,
16527 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;
16528 e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0<b?e.multiplyScalar(1/Math.sqrt(b)):e.set(0,0,0)}}(),barycoordFromPoint:function(){var a=new p,b=new p,c=new p;return function(d,e,f,g,h){a.subVectors(g,e);b.subVectors(f,e);c.subVectors(d,e);d=a.dot(a);e=a.dot(b);f=a.dot(c);var k=b.dot(b);g=b.dot(c);var l=d*k-e*e;h=h||new p;if(0===l)return h.set(-2,-1,-1);l=1/l;k=(k*f-e*g)*l;d=(d*g-e*f)*l;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new p;return function(b,c,d,e){b=
16529 Qa.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=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,
16530 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=
16531 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;e<b.length;e++){b[e].closestPointToPoint(c,!0,d);var h=c.distanceToSquared(d);h<g&&(g=h,f.copy(d))}return f}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});pa.prototype=Object.assign(Object.create(A.prototype),
16532 {constructor:pa,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){A.prototype.copy.call(this,a);this.drawMode=a.drawMode;void 0!==a.morphTargetInfluences&&(this.morphTargetInfluences=a.morphTargetInfluences.slice());void 0!==a.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},a.morphTargetDictionary));return this},updateMorphTargets:function(){var a=this.geometry;if(a.isBufferGeometry){a=a.morphAttributes;var b=Object.keys(a);if(0<b.length){var c=a[b[0]];if(void 0!==
16533 c)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++){var d=c[a].name||String(a);this.morphTargetInfluences.push(0);this.morphTargetDictionary[d]=a}}}else if(c=a.morphTargets,void 0!==c&&0<c.length)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++)d=c[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[d]=a},raycast:function(){function a(a,b,c,d,e,f,g){Qa.barycoordFromPoint(a,b,c,d,v);e.multiplyScalar(v.x);
16534 f.multiplyScalar(v.y);g.multiplyScalar(v.z);e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g,h){if(null===(1===b.side?d.intersectTriangle(g,f,e,!0,h):d.intersectTriangle(e,f,g,2!==b.side,h)))return null;x.copy(h);x.applyMatrix4(a.matrixWorld);b=c.ray.origin.distanceTo(x);return b<c.near||b>c.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,
16535 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),
16536 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;A<C;A+=3){v=x.getX(A);var D=x.getX(A+1);var E=x.getX(A+2);if(y=c(this,t,e,I,z,v,D,E))y.faceIndex=Math.floor(A/3),p.push(y)}}else if(void 0!==I)for(A=0,C=I.count;A<C;A+=3)if(v=A,D=A+1,E=A+2,y=c(this,t,e,I,z,v,D,E))y.index=v,p.push(y)}else if(v.isGeometry){var z=Array.isArray(x);A=v.vertices;
16537 C=v.faces;D=v.faceVertexUvs[0];0<D.length&&(I=D);for(var H=0,N=C.length;H<N;H++){var M=C[H];y=z?x[M.materialIndex]:x;if(void 0!==y){D=A[M.a];E=A[M.b];var V=A[M.c];if(!0===y.morphTargets){var K=v.morphTargets,P=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var Q=0,R=K.length;Q<R;Q++){var O=P[Q];if(0!==O){var S=K[Q].vertices;g.addScaledVector(l.subVectors(S[M.a],D),O);h.addScaledVector(q.subVectors(S[M.b],E),O);k.addScaledVector(n.subVectors(S[M.c],V),O)}}g.add(D);h.add(E);k.add(V);
16538 D=g;E=h;V=k}if(y=b(this,y,t,e,D,E,V,w))I&&I[H]&&(K=I[H],m.copy(K[0]),r.copy(K[1]),u.copy(K[2]),y.uv=a(w,D,E,V,m,r,u)),y.face=M,y.faceIndex=H,p.push(y)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});var ig=0;U.prototype=Object.assign(Object.create(La.prototype),{constructor:U,isPerspectiveCamera:!0,copy:function(a,b){La.prototype.copy.call(this,a,b);this.fov=a.fov;this.zoom=a.zoom;this.near=a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;
16539 this.view=null===a.view?null:Object.assign({},a.view);this.filmGauge=a.filmGauge;this.filmOffset=a.filmOffset;return this},setFocalLength:function(a){a=.5*this.getFilmHeight()/a;this.fov=2*R.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*R.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*R.RAD2DEG*Math.atan(Math.tan(.5*R.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,
16540 1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);this.updateProjectionMatrix()},
16541 updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*R.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==this.view&&this.view.enabled)var g=f.fullWidth,h=f.fullHeight,e=e+f.offsetX*d/g,b=b-f.offsetY*c/h,d=f.width/g*d,c=f.height/h*c;f=this.filmOffset;0!==f&&(e+=a*f/this.getFilmWidth());this.projectionMatrix.makePerspective(e,e+d,b,b-c,a,this.far)},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=
16542 this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});nd.prototype=Object.assign(Object.create(U.prototype),{constructor:nd,isArrayCamera:!0});Ob.prototype.isFogExp2=!0;Ob.prototype.clone=function(){return new Ob(this.color.getHex(),this.density)};Ob.prototype.toJSON=function(){return{type:"FogExp2",color:this.color.getHex(),
16543 density:this.density}};Pb.prototype.isFog=!0;Pb.prototype.clone=function(){return new Pb(this.color.getHex(),this.near,this.far)};Pb.prototype.toJSON=function(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};od.prototype=Object.assign(Object.create(A.prototype),{constructor:od,copy:function(a,b){A.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=
16544 a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=A.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==this.fog&&(b.object.fog=this.fog.toJSON());return b}});Xd.prototype=Object.assign(Object.create(A.prototype),{constructor:Xd,isLensFlare:!0,copy:function(a){A.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=
16545 a.customUpdateCallback;for(var b=0,c=a.lensFlares.length;b<c;b++)this.lensFlares.push(a.lensFlares[b]);return this},add:function(a,b,c,d,e,f){void 0===b&&(b=-1);void 0===c&&(c=0);void 0===f&&(f=1);void 0===e&&(e=new H(16777215));void 0===d&&(d=1);c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c=2*-this.positionScreen.x,d=2*-this.positionScreen.y;
16546 for(a=0;a<b;a++){var e=this.lensFlares[a];e.x=this.positionScreen.x+c*e.distance;e.y=this.positionScreen.y+d*e.distance;e.wantedRotation=e.x*Math.PI*.25;e.rotation+=.25*(e.wantedRotation-e.rotation)}}});Za.prototype=Object.create(Q.prototype);Za.prototype.constructor=Za;Za.prototype.isSpriteMaterial=!0;Za.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};Cc.prototype=Object.assign(Object.create(A.prototype),{constructor:Cc,
16547 isSprite:!0,raycast:function(){var a=new p,b=new p,c=new p;return function(d,e){b.setFromMatrixPosition(this.matrixWorld);d.ray.closestPointToPoint(b,a);c.setFromMatrixScale(this.matrixWorld);var f=c.x*c.y/4;b.distanceToSquared(a)>f||(f=d.ray.origin.distanceTo(a),f<d.near||f>d.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,
16548 a,!1);a=a.levels;for(var b=0,c=a.length;b<c;b++){var d=a[b];this.addLevel(d.object.clone(),d.distance)}return this},addLevel:function(a,b){void 0===b&&(b=0);b=Math.abs(b);for(var c=this.levels,d=0;d<c.length&&!(b<c[d].distance);d++);c.splice(d,0,{distance:b,object:a});this.add(a)},getObjectForDistance:function(a){for(var b=this.levels,c=1,d=b.length;c<d&&!(a<b[c].distance);c++);return b[c-1].object},raycast:function(){var a=new p;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=
16549 b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new p,b=new p;return function(c){var d=this.levels;if(1<d.length){a.setFromMatrixPosition(c.matrixWorld);b.setFromMatrixPosition(this.matrixWorld);c=a.distanceTo(b);d[0].object.visible=!0;for(var e=1,f=d.length;e<f;e++)if(c>=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.levels=
16550 [];for(var b=this.levels,c=0,d=b.length;c<d;c++){var e=b[c];a.object.levels.push({object:e.object.uuid,distance:e.distance})}return a}});Object.assign(Ec.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new K;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){var a,b;var c=0;for(b=this.bones.length;c<b;c++)(a=this.bones[c])&&a.matrixWorld.getInverse(this.boneInverses[c]);c=0;for(b=this.bones.length;c<
16551 b;c++)if(a=this.bones[c])a.parent&&a.parent.isBone?(a.matrix.getInverse(a.parent.matrixWorld),a.matrix.multiply(a.matrixWorld)):a.matrix.copy(a.matrixWorld),a.matrix.decompose(a.position,a.quaternion,a.scale)},update:function(){var a=new K,b=new K;return function(){for(var c=this.bones,d=this.boneInverses,e=this.boneMatrices,f=this.boneTexture,g=0,h=c.length;g<h;g++)a.multiplyMatrices(c[g]?c[g].matrixWorld:b,d[g]),a.toArray(e,16*g);void 0!==f&&(f.needsUpdate=!0)}}(),clone:function(){return new Ec(this.bones,
16552 this.boneInverses)}});pd.prototype=Object.assign(Object.create(A.prototype),{constructor:pd,isBone:!0});qd.prototype=Object.assign(Object.create(pa.prototype),{constructor:qd,isSkinnedMesh:!0,initBones:function(){var a=[],b;if(this.geometry&&void 0!==this.geometry.bones){var c=0;for(b=this.geometry.bones.length;c<b;c++){var d=this.geometry.bones[c];var e=new pd;a.push(e);e.name=d.name;e.position.fromArray(d.pos);e.quaternion.fromArray(d.rotq);void 0!==d.scl&&e.scale.fromArray(d.scl)}c=0;for(b=this.geometry.bones.length;c<
16553 b;c++)d=this.geometry.bones[c],-1!==d.parent&&null!==d.parent&&void 0!==a[d.parent]?a[d.parent].add(a[c]):this.add(a[c])}this.updateMatrixWorld(!0);return a},bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),b=this.matrixWorld);this.bindMatrix.copy(b);this.bindMatrixInverse.getInverse(b)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){var a;if(this.geometry&&this.geometry.isGeometry)for(a=0;a<this.geometry.skinWeights.length;a++){var b=
16554 this.geometry.skinWeights[a];var c=1/b.manhattanLength();Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry){var b=new da,d=this.geometry.attributes.skinWeight;for(a=0;a<d.count;a++)b.x=d.getX(a),b.y=d.getY(a),b.z=d.getZ(a),b.w=d.getW(a),c=1/b.manhattanLength(),Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0),d.setXYZW(a,b.x,b.y,b.z,b.w)}},updateMatrixWorld:function(a){pa.prototype.updateMatrixWorld.call(this,a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):
16555 "detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});O.prototype=Object.create(Q.prototype);O.prototype.constructor=O;O.prototype.isLineBasicMaterial=!0;O.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};
16556 ma.prototype=Object.assign(Object.create(A.prototype),{constructor:ma,isLine:!0,raycast:function(){var a=new K,b=new lb,c=new Da;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&g.computeBoundingSphere();c.copy(g.boundingSphere);c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new p,l=new p,h=new p,q=new p,n=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var m=g.index;var r=g.attributes.position.array;
16557 if(null!==m)for(var u=m.array,g=0,v=u.length-1;g<v;g+=n)m=u[g+1],k.fromArray(r,3*u[g]),l.fromArray(r,3*m),m=b.distanceSqToSegment(k,l,q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),m<d.near||m>d.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;g<v;g+=n)k.fromArray(r,3*g),l.fromArray(r,3*g+3),m=b.distanceSqToSegment(k,l,q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),
16558 m<d.near||m>d.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;g<l-1;g+=n)m=b.distanceSqToSegment(k[g],k[g+1],q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),m<d.near||m>d.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,
16559 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),
16560 {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(f<m){a=b.closestPointToPoint(a);a.applyMatrix4(k);var h=d.ray.origin.distanceTo(a);h<d.near||h>d.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);
16561 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;n<r;n++){var u=t[n];l.fromArray(h,3*u);f(l,u)}else for(n=0,t=h.length/3;n<t;n++)l.fromArray(h,3*n),f(l,n)}else for(l=h.vertices,n=0,t=l.length;n<t;n++)f(l[n],n)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});
16562 Fc.prototype=Object.assign(Object.create(A.prototype),{constructor:Fc});sd.prototype=Object.create(ea.prototype);sd.prototype.constructor=sd;Rb.prototype=Object.create(ea.prototype);Rb.prototype.constructor=Rb;Rb.prototype.isCompressedTexture=!0;Gc.prototype=Object.create(ea.prototype);Gc.prototype.constructor=Gc;Gc.prototype.isDepthTexture=!0;Sb.prototype=Object.create(D.prototype);Sb.prototype.constructor=Sb;Hc.prototype=Object.create(N.prototype);Hc.prototype.constructor=Hc;Tb.prototype=Object.create(D.prototype);
16563 Tb.prototype.constructor=Tb;Ic.prototype=Object.create(N.prototype);Ic.prototype.constructor=Ic;qa.prototype=Object.create(D.prototype);qa.prototype.constructor=qa;Jc.prototype=Object.create(N.prototype);Jc.prototype.constructor=Jc;Ub.prototype=Object.create(qa.prototype);Ub.prototype.constructor=Ub;Kc.prototype=Object.create(N.prototype);Kc.prototype.constructor=Kc;nb.prototype=Object.create(qa.prototype);nb.prototype.constructor=nb;Lc.prototype=Object.create(N.prototype);Lc.prototype.constructor=
16564 Lc;Vb.prototype=Object.create(qa.prototype);Vb.prototype.constructor=Vb;Mc.prototype=Object.create(N.prototype);Mc.prototype.constructor=Mc;Wb.prototype=Object.create(qa.prototype);Wb.prototype.constructor=Wb;Nc.prototype=Object.create(N.prototype);Nc.prototype.constructor=Nc;Xb.prototype=Object.create(D.prototype);Xb.prototype.constructor=Xb;Oc.prototype=Object.create(N.prototype);Oc.prototype.constructor=Oc;Yb.prototype=Object.create(D.prototype);Yb.prototype.constructor=Yb;Pc.prototype=Object.create(N.prototype);
16565 Pc.prototype.constructor=Pc;Zb.prototype=Object.create(D.prototype);Zb.prototype.constructor=Zb;var Ha={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;e<b;d=e++)c+=a[d].x*a[e].y-a[e].x*a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g;if(0<Ha.area(a))for(g=0;g<c;g++)e[g]=g;else for(g=0;g<c;g++)e[g]=c-1-g;var h=2*c;for(g=c-1;2<c;){if(0>=h--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}var k=
16566 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<c;m++){var D=a[e[m]].x;var E=a[e[m]].y;if(!(D===n&&E===p||D===r&&E===u||D===v&&E===w)){var H=D-n;var N=E-p;var K=D-r;var L=E-u;D-=v;E-=w;L=z*L-y*K;N=A*N-x*H;D=B*E-C*D;if(L>=-Number.EPSILON&&D>=-Number.EPSILON&&N>=-Number.EPSILON){x=
16567 !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;l<c;k++,l++)e[k]=e[l];c--;h=2*c}}return b?f:d}}(),triangulateShape:function(a,b){function c(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=c.x&&c.x<=b.x:b.x<=c.x&&c.x<=a.x:a.y<b.y?a.y<=c.y&&c.y<=b.y:b.y<=c.y&&c.y<=a.y}function e(a,b,c,e,f){var g=b.x-a.x,h=b.y-a.y,k=e.x-c.x,l=e.y-c.y,m=a.x-c.x,n=a.y-c.y,q=h*k-g*l,p=h*m-g*n;if(Math.abs(q)>Number.EPSILON){if(0<
16568 q){if(0>p||p>q)return[];k=l*m-k*n;if(0>k||k>q)return[]}else{if(0<p||p<q)return[];k=l*m-k*n;if(0<k||k<q)return[]}if(0===k)return!f||0!==p&&p!==q?[a]:[];if(k===q)return!f||0!==p&&p!==q?[b]:[];if(0===p)return[c];if(p===q)return[e];f=k/q;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==p||l*m!==k*n)return[];h=0===g&&0===h;k=0===k&&0===l;if(h&&k)return a.x!==c.x||a.y!==c.y?[]:[a];if(h)return d(c,e,a)?[a]:[];if(k)return d(a,b,c)?[c]:[];0!==g?(a.x<b.x?(g=a,k=a.x,h=b,a=b.x):(g=b,k=b.x,h=a,a=a.x),c.x<e.x?(b=c,q=c.x,l=
16569 e,c=e.x):(b=e,q=e.x,l=c,c=c.x)):(a.y<b.y?(g=a,k=a.y,h=b,a=b.y):(g=b,k=b.y,h=a,a=a.y),c.y<e.y?(b=c,q=c.y,l=e,c=e.y):(b=e,q=e.y,l=c,c=c.y));return k<=q?a<q?[]:a===q?f?[]:[b]:a<=c?[b,h]:[b,l]:k>c?[]: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,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h={},k=a.concat();var l=0;for(g=b.length;l<g;l++)Array.prototype.push.apply(k,
16570 b[l]);l=0;for(g=k.length;l<g;l++){var m=k[l].x+":"+k[l].y;void 0!==h[m]&&console.warn("THREE.ShapeUtils: Duplicate point",m,l);h[m]=l}l=function(a,b){function c(a,b){var c=h.length-1,d=a-1;0>d&&(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;c<h.length;c++){var d=c+1;d%=h.length;d=e(a,b,h[c],h[d],!0);if(0<d.length)return!0}return!1}function g(a,c){var d,f;for(d=0;d<
16571 k.length;d++){var g=b[k[d]];for(f=0;f<g.length;f++){var h=f+1;h%=g.length;h=e(a,c,g[f],g[h],!0);if(0<h.length)return!0}}return!1}var h=a.concat(),k=[],l,m;a=[];var q,n=0;for(l=b.length;n<l;n++)k.push(n);var p=0;for(var t=2*k.length;0<k.length;){t--;if(0>t){console.log('THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!');break}for(m=p;m<h.length;m++){var y=h[m];l=-1;for(n=0;n<k.length;n++){var C=k[n];var A=y.x+":"+y.y+":"+C;if(void 0===a[A]){var D=
16572 b[C];for(q=0;q<D.length;q++)if(C=D[q],c(m,q)&&!d(y,C)&&!g(y,C)){l=q;k.splice(n,1);p=h.slice(0,m+1);C=h.slice(m);q=D.slice(l);var E=D.slice(0,l+1);h=p.concat(q).concat(E).concat(C);p=m;break}if(0<=l)break;a[A]=!0}}if(0<=l)break}}return h}(a,b);k=Ha.triangulate(l,!1);l=0;for(g=k.length;l<g;l++)for(b=k[l],a=0;3>a;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=
16573 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;d<c;d++)this.addShape(a[d],b);this.setIndex(b.arrays.index);this.addAttribute("position",
16574 new y(b.arrays.position,3));this.addAttribute("uv",new y(b.arrays.uv,2))};Ga.prototype.addShape=function(a,b){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}function d(a,b,c){var d=a.x-b.x;var e=a.y-b.y;var f=c.x-a.x;var g=c.y-a.y,h=d*d+e*e;if(Math.abs(d*g-e*f)>Number.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,
16575 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;e<f;e++){var g=Z*e,l=Z*(e+1),q=b+d+g,n=b+d+l,l=b+c+l;h(b+c+g);h(q);h(l);h(q);h(n);h(l);g=m.length/3;g=E.generateSideWallUV(R,m,g-6,g-3,g-2,g-1);k(g[0]);k(g[1]);k(g[3]);k(g[1]);
16576 k(g[2]);k(g[3])}}}function f(a,b,c){r.push(a);r.push(b);r.push(c)}function g(a,b,c){h(a);h(b);h(c);a=m.length/3;a=E.generateTopUV(R,m,a-3,a-2,a-1);k(a[0]);k(a[1]);k(a[2])}function h(a){n.push(m.length/3);m.push(r[3*a+0]);m.push(r[3*a+1]);m.push(r[3*a+2])}function k(a){t.push(a.x);t.push(a.y)}var l=b.arrays?b.arrays:this.getArrays(),m=l.position,n=l.index,t=l.uv,r=[],l=void 0!==b.amount?b.amount:100,u=void 0!==b.bevelThickness?b.bevelThickness:6,v=void 0!==b.bevelSize?b.bevelSize:u-2,w=void 0!==b.bevelSegments?
16577 b.bevelSegments:3,x=void 0!==b.bevelEnabled?b.bevelEnabled:!0,z=void 0!==b.curveSegments?b.curveSegments:12,A=void 0!==b.steps?b.steps:1,B=b.extrudePath,D=!1,E=void 0!==b.UVGenerator?b.UVGenerator:$a.WorldUVGenerator;if(B){var H=B.getSpacedPoints(A);D=!0;x=!1;var N=void 0!==b.frames?b.frames:B.computeFrenetFrames(A,!1);var K=new p;var Q=new p;var P=new p}x||(v=u=w=0);var L,R=this,z=a.extractPoints(z);a=z.shape;var O=z.holes;if(!Ha.isClockWise(a)){a=a.reverse();var M=0;for(L=O.length;M<L;M++){var V=
16578 O[M];Ha.isClockWise(V)&&(O[M]=V.reverse())}}var S=Ha.triangulateShape(a,O),W=a;M=0;for(L=O.length;M<L;M++)V=O[M],a=a.concat(V);var aa,Z=a.length,U,ca=S.length,z=[],G=0;var X=W.length;var fa=X-1;for(aa=G+1;G<X;G++,fa++,aa++)fa===X&&(fa=0),aa===X&&(aa=0),z[G]=d(W[G],W[fa],W[aa]);var B=[],ea=z.concat();M=0;for(L=O.length;M<L;M++){V=O[M];var da=[];G=0;X=V.length;fa=X-1;for(aa=G+1;G<X;G++,fa++,aa++)fa===X&&(fa=0),aa===X&&(aa=0),da[G]=d(V[G],V[fa],V[aa]);B.push(da);ea=ea.concat(da)}for(fa=0;fa<w;fa++){X=
16579 fa/w;var ga=u*Math.cos(X*Math.PI/2);aa=v*Math.sin(X*Math.PI/2);G=0;for(X=W.length;G<X;G++){var T=c(W[G],z[G],aa);f(T.x,T.y,-ga)}M=0;for(L=O.length;M<L;M++)for(V=O[M],da=B[M],G=0,X=V.length;G<X;G++)T=c(V[G],da[G],aa),f(T.x,T.y,-ga)}aa=v;for(G=0;G<Z;G++)T=x?c(a[G],ea[G],aa):a[G],D?(Q.copy(N.normals[0]).multiplyScalar(T.x),K.copy(N.binormals[0]).multiplyScalar(T.y),P.copy(H[0]).add(Q).add(K),f(P.x,P.y,P.z)):f(T.x,T.y,0);for(X=1;X<=A;X++)for(G=0;G<Z;G++)T=x?c(a[G],ea[G],aa):a[G],D?(Q.copy(N.normals[X]).multiplyScalar(T.x),
16580 K.copy(N.binormals[X]).multiplyScalar(T.y),P.copy(H[X]).add(Q).add(K),f(P.x,P.y,P.z)):f(T.x,T.y,l/A*X);for(fa=w-1;0<=fa;fa--){X=fa/w;ga=u*Math.cos(X*Math.PI/2);aa=v*Math.sin(X*Math.PI/2);G=0;for(X=W.length;G<X;G++)T=c(W[G],z[G],aa),f(T.x,T.y,l+ga);M=0;for(L=O.length;M<L;M++)for(V=O[M],da=B[M],G=0,X=V.length;G<X;G++)T=c(V[G],da[G],aa),D?f(T.x,T.y+H[A-1].y,H[A-1].x+ga):f(T.x,T.y,l+ga)}(function(){var a=m.length/3;if(x){var c=0*Z;for(G=0;G<ca;G++)U=S[G],g(U[2]+c,U[1]+c,U[0]+c);c=Z*(A+2*w);for(G=0;G<
16581 ca;G++)U=S[G],g(U[0]+c,U[1]+c,U[2]+c)}else{for(G=0;G<ca;G++)U=S[G],g(U[2],U[1],U[0]);for(G=0;G<ca;G++)U=S[G],g(U[0]+Z*A,U[1]+Z*A,U[2]+Z*A)}R.addGroup(a,m.length/3-a,void 0!==b.material?b.material:0)})();(function(){var a=m.length/3,c=0;e(W,c);c+=W.length;M=0;for(L=O.length;M<L;M++)V=O[M],e(V,c),c+=V.length;R.addGroup(a,m.length/3-a,void 0!==b.extrudeMaterial?b.extrudeMaterial:1)})();b.arrays||(this.setIndex(n),this.addAttribute("position",new y(m,3)),this.addAttribute("uv",new y(b.arrays.uv,2)))};
16582 $a.WorldUVGenerator={generateTopUV:function(a,b,c,d,e){a=b[3*d];d=b[3*d+1];var f=b[3*e];e=b[3*e+1];return[new C(b[3*c],b[3*c+1]),new C(a,d),new C(f,e)]},generateSideWallUV:function(a,b,c,d,e,f){a=b[3*c];var g=b[3*c+1];c=b[3*c+2];var h=b[3*d],k=b[3*d+1];d=b[3*d+2];var l=b[3*e],m=b[3*e+1];e=b[3*e+2];var n=b[3*f],p=b[3*f+1];b=b[3*f+2];return.01>Math.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);
16583 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=
16584 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);
16585 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,
16586 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,
16587 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;
16588 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;
16589 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=
16590 !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=
16591 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=
16592 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,
16593 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;
16594 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=
16595 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=
16596 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,
16597 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)},
16598 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<g.length;h++)l[h]=g.charCodeAt(h);var m="blob"===k?new Blob([l.buffer],{type:c}):l.buffer;break;case "document":m=(new DOMParser).parseFromString(g,c);break;case "json":m=
16599 JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&b(m);e.manager.itemEnd(a)},0)}catch(t){window.setTimeout(function(){d&&d(t);e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{Ta[a]=[];Ta[a].push({onLoad:b,onProgress:c,onError:d});var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(b){var c=b.target.response;jd.add(a,c);var d=Ta[a];delete Ta[a];if(200===this.status){for(var f=0,g=d.length;f<g;f++){var h=d[f];if(h.onLoad)h.onLoad(c)}e.manager.itemEnd(a)}else if(0===
16600 this.status){console.warn("THREE.FileLoader: HTTP Status 0 received.");f=0;for(g=d.length;f<g;f++)if(h=d[f],h.onLoad)h.onLoad(c);e.manager.itemEnd(a)}else{f=0;for(g=d.length;f<g;f++)if(h=d[f],h.onError)h.onError(b);e.manager.itemEnd(a);e.manager.itemError(a)}},!1);n.addEventListener("progress",function(b){for(var c=Ta[a],d=0,e=c.length;d<e;d++){var f=c[d];if(f.onProgress)f.onProgress(b)}},!1);n.addEventListener("error",function(b){var c=Ta[a];delete Ta[a];for(var d=0,f=c.length;d<f;d++){var g=c[d];
16601 if(g.onError)g.onError(b)}e.manager.itemEnd(a);e.manager.itemError(a)},!1);void 0!==this.responseType&&(n.responseType=this.responseType);void 0!==this.withCredentials&&(n.withCredentials=this.withCredentials);n.overrideMimeType&&n.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");for(h in this.requestHeader)n.setRequestHeader(h,this.requestHeader[h]);n.send(null)}e.manager.itemStart(a);return n}},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=
16602 a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(Qe.prototype,{load:function(a,b,c,d){function e(e){l.load(a[e],function(a){a=g._parser(a,!0);h[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};f+=1;6===f&&(1===a.mipmapCount&&(k.minFilter=1006),k.format=a.format,k.needsUpdate=!0,b&&b(k))},c,d)}var f,g=this,h=[],k=new Rb;
16603 k.image=h;var l=new Ja(this.manager);l.setPath(this.path);l.setResponseType("arraybuffer");if(Array.isArray(a))for(var m=f=0,n=a.length;m<n;++m)e(m);else l.load(a,function(a){a=g._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){h[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)h[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),h[d].format=a.format,h[d].width=a.width,h[d].height=a.height}else k.image.width=a.width,k.image.height=a.height,k.mipmaps=a.mipmaps;1===a.mipmapCount&&
16604 (k.minFilter=1006);k.format=a.format;k.needsUpdate=!0;b&&b(k)},c,d);return k},setPath:function(a){this.path=a;return this}});Object.assign(Zd.prototype,{load:function(a,b,c,d){var e=this,f=new fb,g=new Ja(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==
16605 a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Xc.prototype,{crossOrigin:"Anonymous",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);
16606 if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;c=document.createElementNS("http://www.w3.org/1999/xhtml","img");c.addEventListener("load",function(){jd.add(a,this);b&&b(this);e.manager.itemEnd(a)},!1);c.addEventListener("error",function(b){d&&d(b);e.manager.itemEnd(a);e.manager.itemError(a)},!1);"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(c.crossOrigin=this.crossOrigin);e.manager.itemStart(a);c.src=a;return c},setCrossOrigin:function(a){this.crossOrigin=
16607 a;return this},setPath:function(a){this.path=a;return this}});Object.assign($d.prototype,{crossOrigin:"Anonymous",load:function(a,b,c,d){function e(c){g.load(a[c],function(a){f.images[c]=a;h++;6===h&&(f.needsUpdate=!0,b&&b(f))},void 0,d)}var f=new Ua,g=new Xc(this.manager);g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(td.prototype,
16608 {crossOrigin:"Anonymous",load:function(a,b,c,d){var e=new Xc(this.manager);e.setCrossOrigin(this.crossOrigin);e.setPath(this.path);var f=new ea;f.image=e.load(a,function(){var c=0<a.search(/\.(jpg|jpeg)$/)||0===a.search(/^data\:image\/jpeg/);f.format=c?1022:1023;f.needsUpdate=!0;void 0!==b&&b(f)},c,d);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});ga.prototype=Object.assign(Object.create(A.prototype),{constructor:ga,isLight:!0,copy:function(a){A.prototype.copy.call(this,
16609 a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&
16610 (a.object.shadow=this.shadow.toJSON());return a}});ud.prototype=Object.assign(Object.create(ga.prototype),{constructor:ud,isHemisphereLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.groundColor.copy(a.groundColor);return this}});Object.assign(vb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=
16611 this.bias);1!==this.radius&&(a.radius=this.radius);if(512!==this.mapSize.x||512!==this.mapSize.y)a.mapSize=this.mapSize.toArray();a.camera=this.camera.toJSON(!1).object;delete a.camera.matrix;return a}});vd.prototype=Object.assign(Object.create(vb.prototype),{constructor:vd,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*R.RAD2DEG*a.angle,d=this.mapSize.width/this.mapSize.height;a=a.distance||b.far;if(c!==b.fov||d!==b.aspect||a!==b.far)b.fov=c,b.aspect=d,b.far=a,b.updateProjectionMatrix()}});
16612 wd.prototype=Object.assign(Object.create(ga.prototype),{constructor:wd,isSpotLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});xd.prototype=Object.assign(Object.create(ga.prototype),{constructor:xd,isPointLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();
16613 return this}});yd.prototype=Object.assign(Object.create(vb.prototype),{constructor:yd});zd.prototype=Object.assign(Object.create(ga.prototype),{constructor:zd,isDirectionalLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});Ad.prototype=Object.assign(Object.create(ga.prototype),{constructor:Ad,isAmbientLight:!0});Bd.prototype=Object.assign(Object.create(ga.prototype),{constructor:Bd,isRectAreaLight:!0,copy:function(a){ga.prototype.copy.call(this,
16614 a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=ga.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var T={arraySlice:function(a,b,c){return T.isTypedArray(a)?new a.constructor(a.subarray(b,void 0!==c?c:a.length)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof
16615 DataView)},getKeyframeOrder:function(a){for(var b=a.length,c=Array(b),d=0;d!==b;++d)c[d]=d;c.sort(function(b,c){return a[b]-a[c]});return c},sortedArray:function(a,b,c){for(var d=a.length,e=new a.constructor(d),f=0,g=0;g!==d;++f)for(var h=c[f]*b,k=0;k!==b;++k)e[g++]=a[h+k];return e},flattenJSON:function(a,b,c,d){for(var e=1,f=a[0];void 0!==f&&void 0===f[d];)f=a[e++];if(void 0!==f){var g=f[d];if(void 0!==g)if(Array.isArray(g)){do g=f[d],void 0!==g&&(b.push(f.time),c.push.apply(c,g)),f=a[e++];while(void 0!==
16616 f)}else if(void 0!==g.toArray){do g=f[d],void 0!==g&&(b.push(f.time),g.toArray(c,c.length)),f=a[e++];while(void 0!==f)}else{do g=f[d],void 0!==g&&(b.push(f.time),c.push(g)),f=a[e++];while(void 0!==f)}}}};Object.assign(xa.prototype,{evaluate:function(a){var b=this.parameterPositions,c=this._cachedIndex,d=b[c],e=b[c-1];a:{b:{c:{d:if(!(a<d)){for(var f=c+2;;){if(void 0===d){if(a<e)break d;this._cachedIndex=c=b.length;return this.afterEnd_(c-1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;
16617 break c}if(a>=e)break a;else{f=b[1];a<f&&(c=2,e=f);for(f=c-2;;){if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(c===f)break;d=e;e=b[--c-1];if(a>=e)break b}d=c;c=0}}for(;c<d;)e=c+d>>>1,a<b[e]?d=e:c=e+1;d=b[c];e=b[c-1];if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(void 0===d)return this._cachedIndex=c=b.length,this.afterEnd_(c-1,e,a)}this._cachedIndex=c;this.intervalChanged_(c,e,d)}return this.interpolate_(c,e,a,d)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||
16618 this.DefaultSettings_},copySampleValue_:function(a){var b=this.resultBuffer,c=this.sampleValues,d=this.valueSize;a*=d;for(var e=0;e!==d;++e)b[e]=c[a+e];return b},interpolate_:function(){throw Error("call to abstract method");},intervalChanged_:function(){}});Object.assign(xa.prototype,{beforeStart_:xa.prototype.copySampleValue_,afterEnd_:xa.prototype.copySampleValue_});Cd.prototype=Object.assign(Object.create(xa.prototype),{constructor:Cd,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,
16619 b,c){var d=this.parameterPositions,e=a-2,f=a+1,g=d[e],h=d[f];if(void 0===g)switch(this.getSettings_().endingStart){case 2401:e=a;g=2*b-c;break;case 2402:e=d.length-2;g=b+d[e]-d[e+1];break;default:e=a,g=c}if(void 0===h)switch(this.getSettings_().endingEnd){case 2401:f=a;h=2*c-b;break;case 2402:f=1;h=c+d[1]-d[0];break;default:f=a-1,h=b}a=.5*(c-b);d=this.valueSize;this._weightPrev=a/(b-g);this._weightNext=a/(h-c);this._offsetPrev=e*d;this._offsetNext=f*d},interpolate_:function(a,b,c,d){var e=this.resultBuffer,
16620 f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,l=this._offsetNext,m=this._weightPrev,n=this._weightNext,p=(c-b)/(d-b);c=p*p;d=c*p;b=-m*d+2*m*c-m*p;m=(1+m)*d+(-1.5-2*m)*c+(-.5+m)*p+1;p=(-1-n)*d+(1.5+n)*c+.5*p;n=n*d-n*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+m*f[h+c]+p*f[a+c]+n*f[l+c];return e}});Yc.prototype=Object.assign(Object.create(xa.prototype),{constructor:Yc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-
16621 b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Dd.prototype=Object.assign(Object.create(xa.prototype),{constructor:Dd,interpolate_:function(a){return this.copySampleValue_(a-1)}});var eb={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Dd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Yc(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Cd(this.times,
16622 this.values,this.getValueSize(),a)},setInterpolation:function(a){switch(a){case 2300:var b=this.InterpolantFactoryMethodDiscrete;break;case 2301:b=this.InterpolantFactoryMethodLinear;break;case 2302:b=this.InterpolantFactoryMethodSmooth}if(void 0===b){b="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant)if(a!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(b);console.warn("THREE.KeyframeTrackPrototype:",
16623 b)}else this.createInterpolant=b},getInterpolation:function(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302}},getValueSize:function(){return this.values.length/this.times.length},shift:function(a){if(0!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]+=a;return this},scale:function(a){if(1!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]*=a;return this},
16624 trim:function(a,b){for(var c=this.times,d=c.length,e=0,f=d-1;e!==d&&c[e]<a;)++e;for(;-1!==f&&c[f]>b;)--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.",
16625 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,
16626 b,c=this.times,d=this.values,e=this.getValueSize(),f=2302===this.getInterpolation(),g=1,h=c.length-1,k=1;k<h;++k){a=!1;var l=c[k];if(l!==c[k+1]&&(1!==k||l!==l[0]))if(f)a=!0;else{b=k*e;for(var m=b-e,n=b+e,l=0;l!==e;++l){var p=d[b+l];if(p!==d[m+l]||p!==d[n+l]){a=!0;break}}}if(a){if(k!==g)for(c[g]=c[k],b=k*e,a=g*e,l=0;l!==e;++l)d[a+l]=d[b+l];++g}}if(0<h){c[g]=c[h];b=h*e;a=g*e;for(l=0;l!==e;++l)d[a+l]=d[b+l];++g}g!==c.length&&(this.times=T.arraySlice(c,0,g),this.values=T.arraySlice(d,0,g*e));return this}};
16627 ic.prototype=Object.assign(Object.create(eb),{constructor:ic,ValueTypeName:"vector"});Ed.prototype=Object.assign(Object.create(xa.prototype),{constructor:Ed,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;b=(c-b)/(d-b);for(c=a+g;a!==c;a+=4)Z.slerpFlat(e,0,f,a-g,f,a,b);return e}});Zc.prototype=Object.assign(Object.create(eb),{constructor:Zc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Ed(this.times,
16628 this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});jc.prototype=Object.assign(Object.create(eb),{constructor:jc,ValueTypeName:"number"});Fd.prototype=Object.assign(Object.create(eb),{constructor:Fd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Gd.prototype=Object.assign(Object.create(eb),{constructor:Gd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,
16629 InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Hd.prototype=Object.assign(Object.create(eb),{constructor:Hd,ValueTypeName:"color"});xb.prototype=eb;eb.constructor=xb;Object.assign(xb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=xb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];T.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,
16630 a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{var b={name:a.name,times:T.convertArray(a.times,Array),values:T.convertArray(a.values,Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return jc;case "vector":case "vector2":case "vector3":case "vector4":return ic;
16631 case "color":return Hd;case "quaternion":return Zc;case "bool":case "boolean":return Gd;case "string":return Fd}throw Error("Unsupported typeName: "+a);}});Object.assign(ka,{parse:function(a){for(var b=[],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(xb.parse(c[e]).scale(d));return new ka(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b};for(var d=0,e=c.length;d!==e;++d)b.push(xb.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,
16632 b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%e,g,(g+1)%e);k.push(0,1,0);var l=T.getKeyframeOrder(h),h=T.sortedArray(h,1,l),k=T.sortedArray(k,1,l);d||0!==h[0]||(h.push(e),k.push(k[0]));f.push((new jc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new ka(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(a=0;a<c.length;a++)if(c[a].name===b)return c[a];return null},CreateClipsFromMorphTargetSequences:function(a,
16633 b,c){for(var d,e={},f=/^([\w-]*?)([\d]+)$/,g=0,h=a.length;g<h;g++){var k=a[g],l=k.name.match(f);l&&1<l.length&&(d=l[1],(l=e[d])||(e[d]=l=[]),l.push(k))}a=[];for(d in e)a.push(ka.CreateFromMorphTargetSequence(d,e[d],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];T.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||
16634 -1,g=a.fps||30;a=a.hierarchy||[];for(var h=0;h<a.length;h++){var k=a[h].keys;if(k&&0!==k.length)if(k[0].morphTargets){for(var f={},l=0;l<k.length;l++)if(k[l].morphTargets)for(var m=0;m<k[l].morphTargets.length;m++)f[k[l].morphTargets[m]]=-1;for(var n in f){for(var p=[],r=[],m=0;m!==k[l].morphTargets.length;++m){var u=k[l];p.push(u.time);r.push(u.morphTarget===n?1:0)}d.push(new jc(".morphTargetInfluence["+n+"]",p,r))}f=f.length*(g||1)}else l=".bones["+b[h].name+"]",c(ic,l+".position",k,"pos",d),c(Zc,
16635 l+".quaternion",k,"rot",d),c(ic,l+".scale",k,"scl",d)}return 0===d.length?null:new ka(e,f,d)}});Object.assign(ka.prototype,{resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();return this}});Object.assign(Id.prototype,
16636 {load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=a},parse:function(a){function b(a){void 0===c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new tg[a.type];void 0!==a.uuid&&(d.uuid=a.uuid);void 0!==a.name&&(d.name=a.name);void 0!==a.color&&d.color.setHex(a.color);void 0!==a.roughness&&(d.roughness=a.roughness);void 0!==a.metalness&&(d.metalness=a.metalness);
16637 void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);void 0!==a.clearCoat&&(d.clearCoat=a.clearCoat);void 0!==a.clearCoatRoughness&&(d.clearCoatRoughness=a.clearCoatRoughness);void 0!==a.uniforms&&(d.uniforms=a.uniforms);void 0!==a.vertexShader&&(d.vertexShader=a.vertexShader);void 0!==a.fragmentShader&&(d.fragmentShader=a.fragmentShader);void 0!==a.vertexColors&&(d.vertexColors=a.vertexColors);void 0!==
16638 a.fog&&(d.fog=a.fog);void 0!==a.flatShading&&(d.flatShading=a.flatShading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==a.opacity&&(d.opacity=a.opacity);void 0!==a.transparent&&(d.transparent=a.transparent);void 0!==a.alphaTest&&(d.alphaTest=a.alphaTest);void 0!==a.depthTest&&(d.depthTest=a.depthTest);void 0!==a.depthWrite&&(d.depthWrite=a.depthWrite);void 0!==a.colorWrite&&(d.colorWrite=a.colorWrite);void 0!==a.wireframe&&(d.wireframe=a.wireframe);void 0!==
16639 a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=a.wireframeLinejoin);void 0!==a.rotation&&(d.rotation=a.rotation);1!==a.linewidth&&(d.linewidth=a.linewidth);void 0!==a.dashSize&&(d.dashSize=a.dashSize);void 0!==a.gapSize&&(d.gapSize=a.gapSize);void 0!==a.scale&&(d.scale=a.scale);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=
16640 a.morphTargets);void 0!==a.dithering&&(d.dithering=a.dithering);void 0!==a.visible&&(d.visible=a.visible);void 0!==a.userData&&(d.userData=a.userData);void 0!==a.shading&&(d.flatShading=1===a.shading);void 0!==a.size&&(d.size=a.size);void 0!==a.sizeAttenuation&&(d.sizeAttenuation=a.sizeAttenuation);void 0!==a.map&&(d.map=b(a.map));void 0!==a.alphaMap&&(d.alphaMap=b(a.alphaMap),d.transparent=!0);void 0!==a.bumpMap&&(d.bumpMap=b(a.bumpMap));void 0!==a.bumpScale&&(d.bumpScale=a.bumpScale);void 0!==a.normalMap&&
16641 (d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new C).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=b(a.displacementMap));void 0!==a.displacementScale&&(d.displacementScale=a.displacementScale);void 0!==a.displacementBias&&(d.displacementBias=a.displacementBias);void 0!==a.roughnessMap&&(d.roughnessMap=b(a.roughnessMap));void 0!==a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=
16642 b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));void 0!==a.reflectivity&&(d.reflectivity=a.reflectivity);void 0!==a.lightMap&&(d.lightMap=b(a.lightMap));void 0!==a.lightMapIntensity&&(d.lightMapIntensity=a.lightMapIntensity);void 0!==a.aoMap&&(d.aoMap=b(a.aoMap));void 0!==a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=
16643 b(a.gradientMap));return d}});Object.assign(ae.prototype,{load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new D;var c=a.data.index;void 0!==c&&(c=new gf[c.type](c.array),b.setIndex(new P(c,1)));var d=a.data.attributes;for(f in d){var e=d[f];c=new gf[e.type](e.array);b.addAttribute(f,new P(c,e.itemSize,e.normalized))}var f=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==f)for(c=0,d=f.length;c!==d;++c)e=f[c],
16644 b.addGroup(e.start,e.count,e.materialIndex);a=a.data.boundingSphere;void 0!==a&&(f=new p,void 0!==a.center&&f.fromArray(a.center),b.boundingSphere=new Da(f,a.radius));return b}});var gf={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:"undefined"!==typeof Uint8ClampedArray?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};kc.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,
16645 b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=b[c+1];if(b[c].test(a))return e}return null}};Object.assign(kc.prototype,{crossOrigin:void 0,extractUrlBase:function(a){a=a.split("/");if(1===a.length)return"./";a.pop();return a.join("/")+"/"},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},
16646 b=new H,c=new td,d=new Id;return function(e,f,g){function h(a,b,d,e,h){a=f+a;var l=kc.Handlers.get(a);null!==l?a=l.load(a):(c.setCrossOrigin(g),a=c.load(a));void 0!==b&&(a.repeat.fromArray(b),1!==b[0]&&(a.wrapS=1E3),1!==b[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==e&&("repeat"===e[0]&&(a.wrapS=1E3),"mirror"===e[0]&&(a.wrapS=1002),"repeat"===e[1]&&(a.wrapT=1E3),"mirror"===e[1]&&(a.wrapT=1002));void 0!==h&&(a.anisotropy=h);b=R.generateUUID();k[b]=a;return b}var k={},l={uuid:R.generateUUID(),
16647 type:"MeshLambertMaterial"},m;for(m in e){var n=e[m];switch(m){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":l.name=n;break;case "blending":l.blending=a[n];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",m,"is no longer supported.");break;case "colorDiffuse":l.color=b.fromArray(n).getHex();break;case "colorSpecular":l.specular=b.fromArray(n).getHex();break;case "colorEmissive":l.emissive=b.fromArray(n).getHex();
16648 break;case "specularCoef":l.shininess=n;break;case "shading":"basic"===n.toLowerCase()&&(l.type="MeshBasicMaterial");"phong"===n.toLowerCase()&&(l.type="MeshPhongMaterial");"standard"===n.toLowerCase()&&(l.type="MeshStandardMaterial");break;case "mapDiffuse":l.map=h(n,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":l.emissiveMap=h(n,e.mapEmissiveRepeat,
16649 e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":l.lightMap=h(n,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":l.aoMap=h(n,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;
16650 case "mapBump":l.bumpMap=h(n,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":l.bumpScale=n;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":l.normalMap=h(n,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":l.normalScale=[n,n];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":l.specularMap=
16651 h(n,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":l.metalnessMap=h(n,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":l.roughnessMap=h(n,e.mapRoughnessRepeat,
16652 e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":l.alphaMap=h(n,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":l.side=1;break;case "doubleSided":l.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");
16653 l.opacity=n;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":l[m]=n;break;case "vertexColors":!0===n&&(l.vertexColors=2);"face"===n&&(l.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",m,n)}}"MeshBasicMaterial"===l.type&&delete l.emissive;"MeshPhongMaterial"!==l.type&&delete l.specular;1>l.opacity&&(l.transparent=!0);d.setTextures(k);return d.parse(l)}}()});Object.assign(be.prototype,
16654 {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.");
16655 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;e<d.uvs.length;e++)d.uvs[e].length&&t++;for(e=0;e<t;e++)c.faceVertexUvs[e]=[]}var r=0;for(g=k.length;r<g;)e=new p,e.x=k[r++]*n,e.y=k[r++]*n,e.z=k[r++]*n,c.vertices.push(e);
16656 r=0;for(g=h.length;r<g;){k=h[r++];var u=k&1;var v=k&2;e=k&8;var w=k&16;var x=k&32;n=k&64;k&=128;if(u){u=new Pa;u.a=h[r];u.b=h[r+1];u.c=h[r+3];var z=new Pa;z.a=h[r+1];z.b=h[r+2];z.c=h[r+3];r+=4;v&&(v=h[r++],u.materialIndex=v,z.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++){var y=d.uvs[e];c.faceVertexUvs[e][v]=[];c.faceVertexUvs[e][v+1]=[];for(f=0;4>f;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*
16657 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;e<t;e++)for(y=
16658 d.uvs[e],c.faceVertexUvs[e][v]=[],f=0;3>f;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;g<h;g+=r)c.skinWeights.push(new da(d.skinWeights[g],
16659 1<r?d.skinWeights[g+1]:0,2<r?d.skinWeights[g+2]:0,3<r?d.skinWeights[g+3]:0));if(d.skinIndices)for(g=0,h=d.skinIndices.length;g<h;g+=r)c.skinIndices.push(new da(d.skinIndices[g],1<r?d.skinIndices[g+1]:0,2<r?d.skinIndices[g+2]:0,3<r?d.skinIndices[g+3]:0));c.bones=d.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+
16660 c.skinWeights.length+") should match.");g=a;h=g.scale;if(void 0!==g.morphTargets)for(d=0,r=g.morphTargets.length;d<r;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=g.morphTargets[d].name,c.morphTargets[d].vertices=[],l=c.morphTargets[d].vertices,m=g.morphTargets[d].vertices,t=0,k=m.length;t<k;t+=3)n=new p,n.x=m[t]*h,n.y=m[t+1]*h,n.z=m[t+2]*h,l.push(n);if(void 0!==g.morphColors&&0<g.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),
16661 h=c.faces,g=g.morphColors[0].colors,d=0,r=h.length;d<r;d++)h[d].color.fromArray(g,3*d);g=a;d=[];r=[];void 0!==g.animation&&r.push(g.animation);void 0!==g.animations&&(g.animations.length?r=r.concat(g.animations):r.push(g.animations));for(g=0;g<r.length;g++)(h=ka.parseAnimation(r[g],c.bones))&&d.push(h);c.morphTargets&&(r=ka.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(r));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===
16662 a.materials.length)return{geometry:c};a=kc.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:a}}}()});Object.assign(Re.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ja(e.manager)).load(a,function(c){var f=null;try{f=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=f.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?
16663 console.error("THREE.ObjectLoader: Can't load "+a+". Use THREE.JSONLoader instead."):e.parse(f,b)},c,d)},setTexturePath:function(a){this.texturePath=a},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a,b){var c=this.parseGeometries(a.geometries),d=this.parseImages(a.images,function(){void 0!==b&&b(e)}),d=this.parseTextures(a.textures,d),d=this.parseMaterials(a.materials,d),e=this.parseObject(a.object,c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));void 0!==a.images&&
16664 0!==a.images.length||void 0===b||b(e);return e},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new be,d=new ae,e=0,f=a.length;e<f;e++){var g=a[e];switch(g.type){case "PlaneGeometry":case "PlaneBufferGeometry":var h=new Ca[g.type](g.width,g.height,g.widthSegments,g.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":h=new Ca[g.type](g.width,g.height,g.depth,g.widthSegments,g.heightSegments,g.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":h=
16665 new Ca[g.type](g.radius,g.segments,g.thetaStart,g.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":h=new Ca[g.type](g.radiusTop,g.radiusBottom,g.height,g.radialSegments,g.heightSegments,g.openEnded,g.thetaStart,g.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":h=new Ca[g.type](g.radius,g.height,g.radialSegments,g.heightSegments,g.openEnded,g.thetaStart,g.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":h=new Ca[g.type](g.radius,g.widthSegments,
16666 g.heightSegments,g.phiStart,g.phiLength,g.thetaStart,g.thetaLength);break;case "DodecahedronGeometry":case "DodecahedronBufferGeometry":case "IcosahedronGeometry":case "IcosahedronBufferGeometry":case "OctahedronGeometry":case "OctahedronBufferGeometry":case "TetrahedronGeometry":case "TetrahedronBufferGeometry":h=new Ca[g.type](g.radius,g.detail);break;case "RingGeometry":case "RingBufferGeometry":h=new Ca[g.type](g.innerRadius,g.outerRadius,g.thetaSegments,g.phiSegments,g.thetaStart,g.thetaLength);
16667 break;case "TorusGeometry":case "TorusBufferGeometry":h=new Ca[g.type](g.radius,g.tube,g.radialSegments,g.tubularSegments,g.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":h=new Ca[g.type](g.radius,g.tube,g.tubularSegments,g.radialSegments,g.p,g.q);break;case "LatheGeometry":case "LatheBufferGeometry":h=new Ca[g.type](g.points,g.segments,g.phiStart,g.phiLength);break;case "PolyhedronGeometry":case "PolyhedronBufferGeometry":h=new Ca[g.type](g.vertices,g.indices,g.radius,g.details);
16668 break;case "BufferGeometry":h=d.parse(g);break;case "Geometry":h=c.parse(g,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+g.type+'"');continue}h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);b[g.uuid]=h}return b},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Id;d.setTextures(b);b=0;for(var e=a.length;b<e;b++){var f=a[b];if("MultiMaterial"===f.type){for(var g=[],h=0;h<f.materials.length;h++)g.push(d.parse(f.materials[h]));c[f.uuid]=
16669 g}else c[f.uuid]=d.parse(f)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=ka.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return f.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemEnd(a);d.manager.itemError(a)})}var d=this,e={};if(void 0!==a&&0<a.length){b=new Yd(b);var f=new Xc(b);f.setCrossOrigin(this.crossOrigin);b=0;for(var g=a.length;b<g;b++){var h=a[b],k=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(h.url)?
16670 h.url:d.texturePath+h.url;e[h.uuid]=c(k)}}return e},parseTextures:function(a,b){function c(a,b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={};if(void 0!==a)for(var e=0,f=a.length;e<f;e++){var g=a[e];void 0===g.image&&console.warn('THREE.ObjectLoader: No "image" specified for',g.uuid);void 0===b[g.image]&&console.warn("THREE.ObjectLoader: Undefined image",g.image);var h=new ea(b[g.image]);h.needsUpdate=!0;
16671 h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,ug));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);void 0!==g.center&&h.center.fromArray(g.center);void 0!==g.rotation&&(h.rotation=g.rotation);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],hf),h.wrapT=c(g.wrap[1],hf));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,jf));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,jf));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);
16672 void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(){var a=new K;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",a);return c[a]}function f(a){if(void 0!==a){if(Array.isArray(a)){for(var b=[],c=0,e=a.length;c<e;c++){var f=a[c];void 0===d[f]&&console.warn("THREE.ObjectLoader: Undefined material",f);b.push(d[f])}return b}void 0===d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return d[a]}}switch(b.type){case "Scene":var g=
16673 new od;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new H(b.background));void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Pb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Ob(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new U(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=
16674 Object.assign({},b.view));break;case "OrthographicCamera":g=new Kb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new Ad(b.color,b.intensity);break;case "DirectionalLight":g=new zd(b.color,b.intensity);break;case "PointLight":g=new xd(b.color,b.intensity,b.distance,b.decay);break;case "RectAreaLight":g=new Bd(b.color,b.intensity,b.width,b.height);break;case "SpotLight":g=new wd(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new ud(b.color,
16675 b.groundColor,b.intensity);break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");case "Mesh":g=e(b.geometry);var h=f(b.material);g=g.bones&&0<g.bones.length?new qd(g,h):new pa(g,h);break;case "LOD":g=new Dc;break;case "Line":g=new ma(e(b.geometry),f(b.material),b.mode);break;case "LineLoop":g=new rd(e(b.geometry),f(b.material));break;case "LineSegments":g=new ca(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Qb(e(b.geometry),
16676 f(b.material));break;case "Sprite":g=new Cc(f(b.material));break;case "Group":g=new Fc;break;default:g=new A}g.uuid=b.uuid;void 0!==b.name&&(g.name=b.name);void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(g.position,g.quaternion,g.scale)):(void 0!==b.position&&g.position.fromArray(b.position),void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),void 0!==b.scale&&g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);
16677 void 0!==b.receiveShadow&&(g.receiveShadow=b.receiveShadow);b.shadow&&(void 0!==b.shadow.bias&&(g.shadow.bias=b.shadow.bias),void 0!==b.shadow.radius&&(g.shadow.radius=b.shadow.radius),void 0!==b.shadow.mapSize&&g.shadow.mapSize.fromArray(b.shadow.mapSize),void 0!==b.shadow.camera&&(g.shadow.camera=this.parseObject(b.shadow.camera)));void 0!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);if(void 0!==b.children)for(var h=b.children,k=0;k<h.length;k++)g.add(this.parseObject(h[k],
16678 c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var k=b[h],l=g.getObjectByProperty("uuid",k.object);void 0!==l&&g.addLevel(l,k.distance)}return g}}()});var ug={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},hf={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},jf={NearestFilter:1003,NearestMipMapNearestFilter:1004,
16679 NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};Object.assign(S.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");return null},getPointAt:function(a,b){a=this.getUtoTmapping(a);return this.getPoint(a,b)},getPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));return b},getSpacedPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/
16680 a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){void 0===a&&(a=this.arcLengthDivisions);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c=this.getPoint(0),d,e=0;b.push(0);for(d=1;d<=a;d++){var f=this.getPoint(d/a);e+=f.distanceTo(c);b.push(e);c=f}return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,
16681 b){var c=this.getLengths(),d=c.length;b=b?b:a*c[d-1];for(var e=0,f=d-1,g;e<=f;)if(a=Math.floor(e+(f-e)/2),g=c[a]-b,0>g)e=a+1;else if(0<g)f=a-1;else{f=a;break}a=f;if(c[a]===b)return a/(d-1);e=c[a];return(a+(b-e)/(c[a+1]-e))/(d-1)},getTangent:function(a){var b=a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new p,d=[],e=[],f=
16682 [],g=new p,h=new K,k;for(k=0;k<=a;k++){var l=k/a;d[k]=this.getTangentAt(l);d[k].normalize()}e[0]=new p;f[0]=new p;k=Number.MAX_VALUE;l=Math.abs(d[0].x);var m=Math.abs(d[0].y),n=Math.abs(d[0].z);l<=k&&(k=l,c.set(1,0,0));m<=k&&(k=m,c.set(0,1,0));n<=k&&c.set(0,0,1);g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(R.clamp(d[k-
16683 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<d[0].dot(g.crossVectors(e[0],e[a]))&&(c=-c),k=1;k<=a;k++)e[k].applyMatrix4(h.makeRotationAxis(d[k],c*k)),f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.arcLengthDivisions=a.arcLengthDivisions;return this}});Ka.prototype=Object.create(S.prototype);
16684 Ka.prototype.constructor=Ka;Ka.prototype.isLineCurve=!0;Ka.prototype.getPoint=function(a,b){b=b||new C;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};Ka.prototype.getPointAt=function(a,b){return this.getPoint(a,b)};Ka.prototype.getTangent=function(){return this.v2.clone().sub(this.v1).normalize()};Ka.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};Ab.prototype=Object.assign(Object.create(S.prototype),
16685 {constructor:Ab,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),b=this.curves[this.curves.length-1].getPoint(1);a.equals(b)||this.curves.push(new Ka(b,a))},getPoint:function(a){var b=a*this.getLength(),c=this.getCurveLengths();for(a=0;a<c.length;){if(c[a]>=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=
16686 !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;c<d;c++)b+=this.curves[c].getLength(),a.push(b);return this.cacheLengths=a},getSpacedPoints:function(a){void 0===a&&(a=40);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));this.autoClose&&b.push(b[0]);return b},getPoints:function(a){a=a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++)for(var f=
16687 e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:a),g=0;g<f.length;g++){var h=f[g];c&&c.equals(h)||(b.push(h),c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},copy:function(a){S.prototype.copy.call(this,a);this.curves=[];for(var b=0,c=a.curves.length;b<c;b++)this.curves.push(a.curves[b].clone());this.autoClose=a.autoClose;return this}});Na.prototype=Object.create(S.prototype);Na.prototype.constructor=Na;Na.prototype.isEllipseCurve=
16688 !0;Na.prototype.getPoint=function(a,b){b=b||new C;for(var c=2*Math.PI,d=this.aEndAngle-this.aStartAngle,e=Math.abs(d)<Number.EPSILON;0>d;)d+=c;for(;d>c;)d-=c;d<Number.EPSILON&&(d=e?0:c);!0!==this.aClockwise||e||(d=d===c?-c:d-c);c=this.aStartAngle+a*d;a=this.aX+this.xRadius*Math.cos(c);var f=this.aY+this.yRadius*Math.sin(c);0!==this.aRotation&&(c=Math.cos(this.aRotation),d=Math.sin(this.aRotation),e=a-this.aX,f-=this.aY,a=e*c-f*d+this.aX,f=e*d+f*c+this.aY);return b.set(a,f)};Na.prototype.copy=function(a){S.prototype.copy.call(this,
16689 a);this.aX=a.aX;this.aY=a.aY;this.xRadius=a.xRadius;this.yRadius=a.yRadius;this.aStartAngle=a.aStartAngle;this.aEndAngle=a.aEndAngle;this.aClockwise=a.aClockwise;this.aRotation=a.aRotation;return this};ab.prototype=Object.create(S.prototype);ab.prototype.constructor=ab;ab.prototype.isSplineCurve=!0;ab.prototype.getPoint=function(a,b){b=b||new C;var c=this.points,d=(c.length-1)*a;a=Math.floor(d);var d=d-a,e=c[0===a?a:a-1],f=c[a],g=c[a>c.length-2?c.length-1:a+1],c=c[a>c.length-3?c.length-1:a+2];b.set(Se(d,
16690 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;b<c;b++)this.points.push(a.points[b].clone());return this};bb.prototype=Object.create(S.prototype);bb.prototype.constructor=bb;bb.prototype.isCubicBezierCurve=!0;bb.prototype.getPoint=function(a,b){b=b||new C;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(zb(a,c.x,d.x,e.x,f.x),zb(a,c.y,d.y,e.y,f.y));return b};bb.prototype.copy=function(a){S.prototype.copy.call(this,
16691 a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};cb.prototype=Object.create(S.prototype);cb.prototype.constructor=cb;cb.prototype.isQuadraticBezierCurve=!0;cb.prototype.getPoint=function(a,b){b=b||new C;var c=this.v0,d=this.v1,e=this.v2;b.set(yb(a,c.x,d.x,e.x),yb(a,c.y,d.y,e.y));return b};cb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};var se=Object.assign(Object.create(Ab.prototype),
16692 {setFromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;b<c;b++)this.lineTo(a[b].x,a[b].y)},moveTo:function(a,b){this.currentPoint.set(a,b)},lineTo:function(a,b){var c=new Ka(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new cb(this.currentPoint.clone(),new C(a,b),new C(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new bb(this.currentPoint.clone(),new C(a,
16693 b),new C(c,d),new C(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new ab(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,b,c,d,e,f){this.absellipse(a,b,c,c,d,e,f)},ellipse:function(a,b,c,d,e,f,g,h){this.absellipse(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f,g,h)},absellipse:function(a,b,c,d,
16694 e,f,g,h){a=new Na(a,b,c,d,e,f,g,h);0<this.curves.length&&(b=a.getPoint(0),b.equals(this.currentPoint)||this.lineTo(b.x,b.y));this.curves.push(a);a=a.getPoint(1);this.currentPoint.copy(a)},copy:function(a){Ab.prototype.copy.call(this,a);this.currentPoint.copy(a.currentPoint);return this}});Bb.prototype=se;se.constructor=Bb;Cb.prototype=Object.assign(Object.create(se),{constructor:Cb,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractPoints:function(a){return{shape:this.getPoints(a),
16695 holes:this.getPointsHoles(a)}},copy:function(a){Bb.prototype.copy.call(this,a);this.holes=[];for(var b=0,c=a.holes.length;b<c;b++)this.holes.push(a.holes[b].clone());return this}});Object.assign(ce.prototype,{moveTo:function(a,b){this.currentPath=new Bb;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,b)},quadraticCurveTo:function(a,b,c,d){this.currentPath.quadraticCurveTo(a,b,c,d)},bezierCurveTo:function(a,b,c,d,e,f){this.currentPath.bezierCurveTo(a,
16696 b,c,d,e,f)},splineThru:function(a){this.currentPath.splineThru(a)},toShapes:function(a,b){function c(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=new Cb;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,l=h.y-g.y;if(Math.abs(l)>Number.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.y<g.y||a.y>h.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<=
16697 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;p<r;p++){g=f[p];var u=g.getPoints();var v=e(u);(v=a?!v:v)?(!k&&l[n]&&n++,l[n]={s:new Cb,p:u},l[n].s.curves=g.curves,k&&n++,m[n]=[]):m[n].push({h:g,p:u[0]})}if(!l[0])return c(f);if(1<
16698 l.length){p=!1;a=[];e=0;for(f=l.length;e<f;e++)h[e]=[];e=0;for(f=l.length;e<f;e++)for(g=m[e],v=0;v<g.length;v++){k=g[v];n=!0;for(u=0;u<l.length;u++)d(k.p,l[u].p)&&(e!==u&&a.push({froms:e,tos:u,hole:v}),n?(n=!1,h[u].push(k)):p=!0);n&&h[e].push(k)}0<a.length&&(p||(m=h))}p=0;for(e=l.length;p<e;p++)for(h=l[p].s,b.push(h),a=m[p],f=0,g=a.length;f<g;f++)h.holes.push(a[f].h);return b}});Object.assign(de.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=100);void 0===c&&(c=4);var d=this.data;
16699 a=String(a).split("");var e=b/d.resolution,f=(d.boundingBox.yMax-d.boundingBox.yMin+d.underlineThickness)*e,g=0,h=0;b=[];for(var k=0;k<a.length;k++){var l=a[k];if("\n"===l)g=0,h-=f;else{var m;var n=e;var p=g,r=h;if(l=d.glyphs[l]||d.glyphs["?"]){var u=new ce,v=[];if(l.o)for(var w=l._cachedOutline||(l._cachedOutline=l.o.split(" ")),x=0,y=w.length;x<y;)switch(w[x++]){case "m":var A=w[x++]*n+p;var B=w[x++]*n+r;u.moveTo(A,B);break;case "l":A=w[x++]*n+p;B=w[x++]*n+r;u.lineTo(A,B);break;case "q":var C=w[x++]*
16700 n+p;var D=w[x++]*n+r;var E=w[x++]*n+p;var H=w[x++]*n+r;u.quadraticCurveTo(E,H,C,D);if(m=v[v.length-1]){var N=m.x;m=m.y;for(var K=1;K<=c;K++){var O=K/c;yb(O,N,E,C);yb(O,m,H,D)}}break;case "b":if(C=w[x++]*n+p,D=w[x++]*n+r,E=w[x++]*n+p,H=w[x++]*n+r,A=w[x++]*n+p,B=w[x++]*n+r,u.bezierCurveTo(E,H,A,B,C,D),m=v[v.length-1])for(N=m.x,m=m.y,K=1;K<=c;K++)O=K/c,zb(O,N,E,A,C),zb(O,m,H,B,D)}n={offsetX:l.ha*n,path:u}}else n=void 0;g+=n.offsetX;b.push(n.path)}}c=[];d=0;for(a=b.length;d<a;d++)Array.prototype.push.apply(c,
16701 b[d].toShapes());return c}});Object.assign(Te.prototype,{load:function(a,b,c,d){var e=this,f=new Ja(this.manager);f.setPath(this.path);f.load(a,function(a){try{var c=JSON.parse(a)}catch(k){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead."),c=JSON.parse(a.substring(65,a.length-2))}a=e.parse(c);b&&b(a)},c,d)},parse:function(a){return new de(a)},setPath:function(a){this.path=a;return this}});var Md,ge={getContext:function(){void 0===Md&&(Md=new (window.AudioContext||
16702 window.webkitAudioContext));return Md},setContext:function(a){Md=a}};Object.assign(ee.prototype,{load:function(a,b,c,d){var e=new Ja(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){ge.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(Ue.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new K,l=new K;return function(m){if(a!==this||b!==m.focus||c!==m.fov||d!==m.aspect*this.aspect||e!==m.near||f!==m.far||g!==m.zoom||h!==this.eyeSep){a=this;b=m.focus;c=m.fov;
16703 d=m.aspect*this.aspect;e=m.near;f=m.far;g=m.zoom;var n=m.projectionMatrix.clone();h=this.eyeSep/2;var q=h*e/b,p=e*Math.tan(R.DEG2RAD*c*.5)/g;l.elements[12]=-h;k.elements[12]=h;var u=-p*d+q;var v=p*d+q;n.elements[0]=2*e/(v-u);n.elements[8]=(v+u)/(v-u);this.cameraL.projectionMatrix.copy(n);u=-p*d-q;v=p*d-q;n.elements[0]=2*e/(v-u);n.elements[8]=(v+u)/(v-u);this.cameraR.projectionMatrix.copy(n)}this.cameraL.matrixWorld.copy(m.matrixWorld).multiply(l);this.cameraR.matrixWorld.copy(m.matrixWorld).multiply(k)}}()});
16704 $c.prototype=Object.create(A.prototype);$c.prototype.constructor=$c;fe.prototype=Object.assign(Object.create(A.prototype),{constructor:fe,getInput:function(){return this.gain},removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null)},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):
16705 this.gain.disconnect(this.context.destination);this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination)},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(a){this.gain.gain.value=a},updateMatrixWorld:function(){var a=new p,b=new Z,c=new p,d=new p;return function(e){A.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,
16706 this.context.currentTime),e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,
16707 d.y,d.z,f.x,f.y,f.z))}}()});lc.prototype=Object.assign(Object.create(A.prototype),{constructor:lc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
16708 else{var a=this.context.createBufferSource();a.buffer=this.buffer;a.loop=this.loop;a.onended=this.onEnded.bind(this);a.playbackRate.setValueAtTime(this.playbackRate,this.startTime);this.startTime=this.context.currentTime;a.start(this.startTime,this.offset);this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return!0===this.isPlaying&&(this.source.stop(),this.offset+=(this.context.currentTime-
16709 this.startTime)*this.playbackRate,this.isPlaying=!1),this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.offset=0,this.isPlaying=!1,this},connect:function(){if(0<this.filters.length){this.source.connect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].connect(this.filters[a]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());
16710 return this},disconnect:function(){if(0<this.filters.length){this.source.disconnect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].disconnect(this.filters[a]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this},getFilters:function(){return this.filters},setFilters:function(a){a||(a=[]);!0===this.isPlaying?(this.disconnect(),this.filters=a,this.connect()):this.filters=a;return this},getFilter:function(){return this.getFilters()[0]},
16711 setFilter:function(a){return this.setFilters(a?[a]:[])},setPlaybackRate:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.playbackRate=a,!0===this.isPlaying&&this.source.playbackRate.setValueAtTime(this.playbackRate,this.context.currentTime),this},getPlaybackRate:function(){return this.playbackRate},onEnded:function(){this.isPlaying=!1},getLoop:function(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),
16712 !1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.value=a;return this}});he.prototype=Object.assign(Object.create(lc.prototype),{constructor:he,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=
16713 a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=a},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a},updateMatrixWorld:function(){var a=new p;return function(b){A.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,
16714 a.y,a.z)}}()});Object.assign(ie.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=b[c];return a/b.length}});Object.assign(je.prototype,{accumulate:function(a,b){var c=this.buffer,d=this.valueSize;a=a*d+d;var e=this.cumulativeWeight;if(0===e){for(e=0;e!==d;++e)c[a+e]=c[e];e=b}else e+=b,this._mixBufferRegion(c,a,0,b/e,d);this.cumulativeWeight=e},apply:function(a){var b=
16715 this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&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=
16716 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_,
16717 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+
16718 "$"),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: "+
16719 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<a.bones.length;c++){var d=a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var e=a[c];if(e.name===b||e.uuid===b||(e=d(e.children)))return e}return null};if(a=d(a.children))return a}return null}});Object.assign(na.prototype,{_getValue_unavailable:function(){},
16720 _setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.targetObject[this.propertyName]=
16721 a[b]},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=
16722 !0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]],
16723 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=na.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("THREE.PropertyBinding: Can not bind to material as node does not have a material.",
16724 this);return}if(!a.material.materials){console.error("THREE.PropertyBinding: 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("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}a=a.skeleton.bones;for(c=0;c<a.length;c++)if(a[c].name===f){f=c;break}break;default:if(void 0===a[c]){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",
16725 this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error("THREE.PropertyBinding: Trying to update property for track: "+b.nodeName+"."+d+" but it wasn't found.",a);else{b=this.Versioning.None;void 0!==a.needsUpdate?(b=this.Versioning.NeedsUpdate,this.targetObject=a):void 0!==a.matrixWorldNeedsUpdate&&(b=this.Versioning.MatrixWorldNeedsUpdate,this.targetObject=
16726 a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===d){if(!a.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(a.geometry.isBufferGeometry){if(!a.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}for(c=0;c<this.node.geometry.morphAttributes.position.length;c++)if(a.geometry.morphAttributes.position[c].name===
16727 e){e=c;break}}else{if(!a.geometry.morphTargets){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.",this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?(c=this.BindingType.HasFromToArray,this.resolvedProperty=f):Array.isArray(f)?(c=this.BindingType.EntireArray,
16728 this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error("THREE.PropertyBinding: Trying to update node for track: "+this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(na.prototype,{_getValue_unbound:na.prototype.getValue,_setValue_unbound:na.prototype.setValue});Object.assign(We.prototype,
16729 {isAnimationObjectGroup:!0,add:function(){for(var a=this._objects,b=a.length,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._paths,f=this._parsedPaths,g=this._bindings,h=g.length,k=0,l=arguments.length;k!==l;++k){var m=arguments[k],n=m.uuid,p=d[n];if(void 0===p){p=b++;d[n]=p;a.push(m);for(var n=0,r=h;n!==r;++n)g[n].push(new na(m,e[n],f[n]))}else if(p<c){var u=--c,r=a[u];d[r.uuid]=p;a[p]=r;d[n]=u;a[u]=m;n=0;for(r=h;n!==r;++n){var v=g[n],w=v[p];v[p]=v[u];void 0===w&&(w=new na(m,e[n],f[n]));v[u]=
16730 w}}else void 0!==a[p]&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=c},remove:function(){for(var a=this._objects,b=this.nCachedObjects_,c=this._indicesByUUID,d=this._bindings,e=d.length,f=0,g=arguments.length;f!==g;++f){var h=arguments[f],k=h.uuid,l=c[k];if(void 0!==l&&l>=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=
16731 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],m<e){var n=--e,p=c[n];b=--d;a=c[b];f[p.uuid]=m;c[m]=p;f[a.uuid]=n;c[n]=a;c.pop();for(var p=0,r=h;p!==r;++p){a=g[p];var u=a[b];a[m]=a[n];a[n]=u;a.pop()}}else for(b=--d,a=c[b],f[a.uuid]=m,c[m]=a,c.pop(),p=0,r=h;p!==r;++p)a=g[p],a[m]=
16732 a[b],a.pop()}this.nCachedObjects_=e},subscribe_:function(a,b){var c=this._bindingsIndicesByPath,d=c[a],e=this._bindings;if(void 0!==d)return e[d];var f=this._paths,g=this._parsedPaths,h=this._objects,k=this.nCachedObjects_,l=Array(h.length),d=e.length;c[a]=d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new na(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=
16733 f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}});Object.assign(Xe.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=!1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)},
16734 isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(a){this._startTime=a;return this},setLoop:function(a,b){this.loop=a;this.repetitions=b;return this},setEffectiveWeight:function(a){this.weight=a;this._effectiveWeight=this.enabled?a:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(a){return this._scheduleFading(a,0,1)},fadeOut:function(a){return this._scheduleFading(a,1,0)},crossFadeFrom:function(a,b,c){a.fadeOut(b);
16735 this.fadeIn(b);if(c){c=this._clip.duration;var d=a._clip.duration,e=c/d;a.warp(1,d/c,b);this.warp(e,1,b)}return this},crossFadeTo:function(a,b,c){return a.crossFadeFrom(this,b,c)},stopFading:function(){var a=this._weightInterpolant;null!==a&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},setEffectiveTimeScale:function(a){this.timeScale=a;this._effectiveTimeScale=this.paused?0:a;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},
16736 setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,b,c){var d=this._mixer,e=d.time,f=this._timeScaleInterpolant,g=this.timeScale;null===f&&(this._timeScaleInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;d[1]=e+c;f[0]=a/g;f[1]=b/g;return this},stopWarping:function(){var a=
16737 this._timeScaleInterpolant;null!==a&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||this._mixer._root},_update:function(a,b,c,d){if(this.enabled){var e=this._startTime;if(null!==e){b=(a-e)*c;if(0>b||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0<a){b=this._interpolants;
16738 for(var e=this._propertyBindings,f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}}else this._updateWeight(a)},_updateWeight:function(a){var b=0;if(this.enabled){var b=this.weight,c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.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],
16739 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;
16740 -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=0<a?c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(0===g?(a=0>a,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=
16741 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,
16742 {_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,
16743 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,
16744 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},
16745 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&&a<this._nActiveActions},_addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=f.knownActions,a._byClipCacheIndex=b.length,b.push(a));a._cacheIndex=d.length;d.push(a);
16746 f.actionByRoot[c]=a},_removeInactiveAction:function(a){var b=this._actions,c=b[b.length-1],d=a._cacheIndex;c._cacheIndex=d;b[d]=c;b.pop();a._cacheIndex=null;var b=a._clip.uuid,c=this._actionsByClip,d=c[b],e=d.knownActions,f=e[e.length-1],g=a._byClipCacheIndex;f._byClipCacheIndex=g;e[g]=f;e.pop();a._byClipCacheIndex=null;delete d.actionByRoot[(a._localRoot||this._root).uuid];0===e.length&&delete c[b];this._removeInactiveBindingsForAction(a)},_removeInactiveBindingsForAction:function(a){a=a._propertyBindings;
16747 for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,d=this._nActiveActions++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=
16748 e);e[c]=a;a._cacheIndex=f.length;f.push(a)},_removeInactiveBinding:function(a){var b=this._bindings,c=a.binding,d=c.rootNode.uuid,c=c.path,e=this._bindingsByRootAndName,f=e[d],g=b[b.length-1];a=a._cacheIndex;g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=
16749 --this._nActiveBindings,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_lendControlInterpolant:function(){var a=this._controlInterpolants,b=this._nActiveControlInterpolants++,c=a[b];void 0===c&&(c=new Yc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;
16750 b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?ka.findByName(c,a):a;a=null!==c?c.uuid:a;var e=this._actionsByClip[a],f=null;if(void 0!==e){f=e.actionByRoot[d];if(void 0!==f)return f;f=e.knownActions[0];null===c&&(c=f._clip)}if(null===c)return null;b=new Xe(this,c,b);this._bindAction(b,f);this._addInactiveAction(b,a,d);return b},existingAction:function(a,b){var c=b||this._root;b=c.uuid;c="string"===typeof a?ka.findByName(c,
16751 a):a;a=this._actionsByClip[c?c.uuid:a];return void 0!==a?a.actionByRoot[b]||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)b[g]._update(d,a,e,f);a=this._bindings;
16752 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=
16753 this._actionsByClip;for(d in b){var c=b[d].actionByRoot[a];void 0!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}var d=this._bindingsByRootAndName[a];if(void 0!==d)for(var e in d)a=d[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){a=this.existingAction(a,b);null!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}});Jd.prototype.clone=function(){return new Jd(void 0===this.value.clone?this.value:this.value.clone())};ke.prototype=Object.assign(Object.create(D.prototype),
16754 {constructor:ke,isInstancedBufferGeometry:!0,copy:function(a){D.prototype.copy.call(this,a);this.maxInstancedCount=a.maxInstancedCount;return this},clone:function(){return(new this.constructor).copy(this)}});Object.defineProperties(le.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(le.prototype,{isInterleavedBufferAttribute:!0,setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*
16755 this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+this.offset+2]=b;return this},setW:function(a,b){this.data.array[a*this.data.stride+this.offset+3]=b;return this},getX:function(a){return this.data.array[a*this.data.stride+this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+
16756 3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+3]=e;return this}});Object.defineProperty(mc.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});
16757 Object.assign(mc.prototype,{isInterleavedBuffer:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.stride:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+
16758 d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=a;return this}});me.prototype=Object.assign(Object.create(mc.prototype),{constructor:me,isInstancedInterleavedBuffer:!0,copy:function(a){mc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});ne.prototype=Object.assign(Object.create(P.prototype),{constructor:ne,isInstancedBufferAttribute:!0,
16759 copy:function(a){P.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(Ze.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):
16760 console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];oe(a,this,c,b);c.sort($e);return c},intersectObjects:function(a,b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;d<e;d++)oe(a[d],this,c,b);c.sort($e);return c}});Object.assign(af.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=
16761 0;this.running=!0},stop:function(){this.getElapsedTime();this.autoStart=this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){var b=("undefined"===typeof performance?Date:performance).now(),a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}});Object.assign(bf.prototype,{set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},
16762 copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-1E-6,this.phi));return this},setFromVector3:function(a){this.radius=a.length();0===this.radius?this.phi=this.theta=0:(this.theta=Math.atan2(a.x,a.z),this.phi=Math.acos(R.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(cf.prototype,{set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},
16763 copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=Math.sqrt(a.x*a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});ad.prototype=Object.create(A.prototype);ad.prototype.constructor=ad;ad.prototype.isImmediateRenderObject=!0;bd.prototype=Object.create(ca.prototype);bd.prototype.constructor=bd;bd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){var d,e=["a","b","c"];this.object.updateMatrixWorld(!0);
16764 c.getNormalMatrix(this.object.matrixWorld);var f=this.object.matrixWorld,g=this.geometry.attributes.position;if((d=this.object.geometry)&&d.isGeometry)for(var h=d.vertices,k=d.faces,l=d=0,m=k.length;l<m;l++)for(var n=k[l],p=0,r=n.vertexNormals.length;p<r;p++){var u=n.vertexNormals[p];a.copy(h[n[e[p]]]).applyMatrix4(f);b.copy(u).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);g.setXYZ(d,a.x,a.y,a.z);d+=1;g.setXYZ(d,b.x,b.y,b.z);d+=1}else if(d&&d.isBufferGeometry)for(e=d.attributes.position,
16765 h=d.attributes.normal,p=d=0,r=e.count;p<r;p++)a.set(e.getX(p),e.getY(p),e.getZ(p)).applyMatrix4(f),b.set(h.getX(p),h.getY(p),h.getZ(p)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),g.setXYZ(d,a.x,a.y,a.z),d+=1,g.setXYZ(d,b.x,b.y,b.z),d+=1;g.needsUpdate=!0}}();nc.prototype=Object.create(A.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};nc.prototype.update=function(){var a=new p,b=new p;return function(){this.light.updateMatrixWorld();
16766 var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}();oc.prototype=Object.create(ca.prototype);oc.prototype.constructor=oc;oc.prototype.updateMatrixWorld=function(){var a=new p,b=new K,c=new K;return function(d){var e=
16767 this.bones,f=this.geometry,g=f.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var h=0,k=0;h<e.length;h++){var l=e[h];l.parent&&l.parent.isBone&&(b.multiplyMatrices(c,l.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k,a.x,a.y,a.z),b.multiplyMatrices(c,l.parent.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k+1,a.x,a.y,a.z),k+=2)}f.getAttribute("position").needsUpdate=!0;A.prototype.updateMatrixWorld.call(this,d)}}();pc.prototype=Object.create(pa.prototype);pc.prototype.constructor=
16768 pc;pc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};pc.prototype.update=function(){void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)};qc.prototype=Object.create(A.prototype);qc.prototype.constructor=qc;qc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};qc.prototype.update=function(){var a=.5*this.light.width,b=.5*this.light.height,c=this.line.geometry.attributes.position,
16769 d=c.array;d[0]=a;d[1]=-b;d[2]=0;d[3]=a;d[4]=b;d[5]=0;d[6]=-a;d[7]=b;d[8]=0;d[9]=-a;d[10]=-b;d[11]=0;d[12]=a;d[13]=-b;d[14]=0;c.needsUpdate=!0;void 0!==this.color?this.line.material.color.set(this.color):this.line.material.color.copy(this.light.color)};rc.prototype=Object.create(A.prototype);rc.prototype.constructor=rc;rc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};rc.prototype.update=function(){var a=new p,b=new H,c=new H;return function(){var d=
16770 this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{var e=d.geometry.getAttribute("color");b.copy(this.light.color);c.copy(this.light.groundColor);for(var f=0,g=e.count;f<g;f++){var h=f<g/2?b:c;e.setXYZ(f,h.r,h.g,h.b)}e.needsUpdate=!0}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate())}}();cd.prototype=Object.create(ca.prototype);cd.prototype.constructor=cd;Kd.prototype=Object.create(ca.prototype);Kd.prototype.constructor=Kd;dd.prototype=Object.create(ca.prototype);
16771 dd.prototype.constructor=dd;dd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=0,k=0,l=f.length;k<l;k++){var m=f[k],n=m.normal;a.copy(g[m.a]).add(g[m.b]).add(g[m.c]).divideScalar(3).applyMatrix4(d);b.copy(n).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,
16772 a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0}}();sc.prototype=Object.create(A.prototype);sc.prototype.constructor=sc;sc.prototype.dispose=function(){this.lightPlane.geometry.dispose();this.lightPlane.material.dispose();this.targetLine.geometry.dispose();this.targetLine.material.dispose()};sc.prototype.update=function(){var a=new p,b=new p,c=new p;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,
16773 a);this.lightPlane.lookAt(c);void 0!==this.color?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color));this.targetLine.lookAt(c);this.targetLine.scale.z=c.length()}}();ed.prototype=Object.create(ca.prototype);ed.prototype.constructor=ed;ed.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=b.getAttribute("position"),
16774 h=0,k=a.length;h<k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new p,e=new La;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",
16775 0,1,-1);b.getAttribute("position").needsUpdate=!0}}();Db.prototype=Object.create(ca.prototype);Db.prototype.constructor=Db;Db.prototype.update=function(){var a=new Oa;return function(b){void 0!==b&&console.warn("THREE.BoxHelper: .update() has no longer arguments.");void 0!==this.object&&a.setFromObject(this.object);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=
16776 c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}();Db.prototype.setFromObject=function(a){this.object=a;this.update();return this};fd.prototype=Object.create(ca.prototype);fd.prototype.constructor=fd;fd.prototype.updateMatrixWorld=function(a){var b=this.box;b.isEmpty()||(b.getCenter(this.position),b.getSize(this.scale),this.scale.multiplyScalar(.5),A.prototype.updateMatrixWorld.call(this,
16777 a))};gd.prototype=Object.create(ma.prototype);gd.prototype.constructor=gd;gd.prototype.updateMatrixWorld=function(a){var b=-this.plane.constant;1E-8>Math.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){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,
16778 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,
16779 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+=0<e?0:(Math.floor(Math.abs(e)/c.length)+1)*c.length:0===a&&e===d-1&&(e=d-2,a=1);if(this.closed||0<e)var f=c[(e-1)%d];else Nd.subVectors(c[0],c[1]).add(c[0]),f=Nd;var g=c[e%d];var h=c[(e+1)%d];this.closed||e+2<d?c=c[(e+2)%d]:(Nd.subVectors(c[d-
16780 1],c[d-2]).add(c[d-1]),c=Nd);if("centripetal"===this.curveType||"chordal"===this.curveType){var k="chordal"===this.curveType?.5:.25,d=Math.pow(f.distanceToSquared(g),k),e=Math.pow(g.distanceToSquared(h),k),k=Math.pow(h.distanceToSquared(c),k);1E-4>e&&(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,
16781 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<c;b++)this.points.push(a.points[b].clone());this.closed=a.closed;this.curveType=a.curveType;this.tension=a.tension;return this};Fb.prototype=Object.create(S.prototype);Fb.prototype.constructor=Fb;Fb.prototype.isCubicBezierCurve3=
16782 !0;Fb.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(zb(a,c.x,d.x,e.x,f.x),zb(a,c.y,d.y,e.y,f.y),zb(a,c.z,d.z,e.z,f.z));return b};Fb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};Gb.prototype=Object.create(S.prototype);Gb.prototype.constructor=Gb;Gb.prototype.isQuadraticBezierCurve3=!0;Gb.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,
16783 e=this.v2;b.set(yb(a,c.x,d.x,e.x),yb(a,c.y,d.y,e.y),yb(a,c.z,d.z,e.z));return b};Gb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};db.prototype=Object.create(S.prototype);db.prototype.constructor=db;db.prototype.isLineCurve3=!0;db.prototype.getPoint=function(a,b){b=b||new p;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};db.prototype.getPointAt=function(a,b){return this.getPoint(a,
16784 b)};db.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};id.prototype=Object.create(Na.prototype);id.prototype.constructor=id;id.prototype.isArcCurve=!0;S.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(S.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Object.assign(Ab.prototype,{createPointsGeometry:function(a){console.warn("THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");
16785 a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){console.warn("THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){console.warn("THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");for(var b=new N,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new p(e.x,
16786 e.y,e.z||0))}return b}});Object.assign(Bb.prototype,{fromPoints:function(a){console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints().");this.setFromPoints(a)}});ef.prototype=Object.create(ya.prototype);ff.prototype=Object.create(ya.prototype);re.prototype=Object.create(ya.prototype);Object.assign(re.prototype,{initFromArray:function(){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},
16787 reparametrizeByArcLength:function(){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});cd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};oc.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(kd.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},
16788 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(Oa.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},
16789 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)}});
16790 Mb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)};Object.assign(R,{random16:function(){console.warn("THREE.Math: .random16() has been deprecated. Use Math.random() instead.");return Math.random()},nearestPowerOfTwo:function(a){console.warn("THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().");return R.floorPowerOfTwo(a)},nextPowerOfTwo:function(a){console.warn("THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().");
16791 return R.ceilPowerOfTwo(a)}});Object.assign(ra.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(a){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
16792 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(K.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;
16793 return function(){void 0===a&&(a=new p);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");return a.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");
16794 return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector3Array:function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},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.");
16795 return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},applyToBuffer:function(a){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
16796 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(a,b,c,d,e,f){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(a,b,d,c,e,f)}});Aa.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};
16797 Z.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(lb.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)},
16798 isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(Cb.prototype,{extractAllPoints:function(a){console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.");return this.extractPoints(a)},extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new $a(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");
16799 return new cc(this,a)}});Object.assign(C.prototype,{fromAttribute:function(a,b,c){console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});
16800 Object.assign(p.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)},
16801 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)},applyProjection:function(a){console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.");return this.applyMatrix4(a)},fromAttribute:function(a,
16802 b,c){console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});Object.assign(da.prototype,{fromAttribute:function(a,
16803 b,c){console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},lengthManhattan:function(){console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});N.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(A.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
16804 return this.getObjectByName(a)},renderDepth:function(){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(A.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.");
16805 this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(Dc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Ec.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},
16806 set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(S.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");return this.arcLengthDivisions},set:function(a){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=a}});U.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");
16807 void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(ga.prototype,{onlyShadow:{set:function(){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.");
16808 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.");
16809 this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){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(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(a){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.");
16810 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(P.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(D.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,
16811 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.")}});
16812 Object.defineProperties(D.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(Jd.prototype,{dynamic:{set:function(){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.");
16813 return this}}});Object.defineProperties(Q.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new H}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.")},set:function(a){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");
16814 this.flatShading=1===a}}});Object.defineProperties(Ia.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});Object.defineProperties(oa.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},
16815 set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Wd.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()},getMaxAnisotropy:function(){console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().");return this.capabilities.getMaxAnisotropy()},getPrecision:function(){console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.");
16816 return this.capabilities.precision},resetGLState:function(){console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset().");return this.state.reset()},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' ).");
16817 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")},
16818 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(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");
16819 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.")},
16820 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Wd.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.");
16821 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(Ie.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(Hb.prototype,
16822 {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.");
16823 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.");
16824 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},
16825 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.");
16826 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}}});lc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new ee).load(a,function(a){b.setBuffer(a)});return this};
16827 ie.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};$c.prototype.updateCubeMap=function(a,b){console.warn("THREE.CubeCamera: .updateCubeMap() is now .update().");return this.update(a,b)};m.WebGLRenderTargetCube=Ib;m.WebGLRenderTarget=Hb;m.WebGLRenderer=Wd;m.ShaderLib=mb;m.UniformsLib=E;m.UniformsUtils=Ea;m.ShaderChunk=W;m.FogExp2=Ob;m.Fog=Pb;m.Scene=od;m.LensFlare=Xd;m.Sprite=Cc;m.LOD=Dc;m.SkinnedMesh=qd;m.Skeleton=
16828 Ec;m.Bone=pd;m.Mesh=pa;m.LineSegments=ca;m.LineLoop=rd;m.Line=ma;m.Points=Qb;m.Group=Fc;m.VideoTexture=sd;m.DataTexture=fb;m.CompressedTexture=Rb;m.CubeTexture=Ua;m.CanvasTexture=tc;m.DepthTexture=Gc;m.Texture=ea;m.CompressedTextureLoader=Qe;m.DataTextureLoader=Zd;m.CubeTextureLoader=$d;m.TextureLoader=td;m.ObjectLoader=Re;m.MaterialLoader=Id;m.BufferGeometryLoader=ae;m.DefaultLoadingManager=wa;m.LoadingManager=Yd;m.JSONLoader=be;m.ImageLoader=Xc;m.FontLoader=Te;m.FileLoader=Ja;m.Loader=kc;m.Cache=
16829 jd;m.AudioLoader=ee;m.SpotLightShadow=vd;m.SpotLight=wd;m.PointLight=xd;m.RectAreaLight=Bd;m.HemisphereLight=ud;m.DirectionalLightShadow=yd;m.DirectionalLight=zd;m.AmbientLight=Ad;m.LightShadow=vb;m.Light=ga;m.StereoCamera=Ue;m.PerspectiveCamera=U;m.OrthographicCamera=Kb;m.CubeCamera=$c;m.ArrayCamera=nd;m.Camera=La;m.AudioListener=fe;m.PositionalAudio=he;m.AudioContext=ge;m.AudioAnalyser=ie;m.Audio=lc;m.VectorKeyframeTrack=ic;m.StringKeyframeTrack=Fd;m.QuaternionKeyframeTrack=Zc;m.NumberKeyframeTrack=
16830 jc;m.ColorKeyframeTrack=Hd;m.BooleanKeyframeTrack=Gd;m.PropertyMixer=je;m.PropertyBinding=na;m.KeyframeTrack=xb;m.AnimationUtils=T;m.AnimationObjectGroup=We;m.AnimationMixer=Ye;m.AnimationClip=ka;m.Uniform=Jd;m.InstancedBufferGeometry=ke;m.BufferGeometry=D;m.Geometry=N;m.InterleavedBufferAttribute=le;m.InstancedInterleavedBuffer=me;m.InterleavedBuffer=mc;m.InstancedBufferAttribute=ne;m.Face3=Pa;m.Object3D=A;m.Raycaster=Ze;m.Layers=Pd;m.EventDispatcher=ja;m.Clock=af;m.QuaternionLinearInterpolant=Ed;
16831 m.LinearInterpolant=Yc;m.DiscreteInterpolant=Dd;m.CubicInterpolant=Cd;m.Interpolant=xa;m.Triangle=Qa;m.Math=R;m.Spherical=bf;m.Cylindrical=cf;m.Plane=Aa;m.Frustum=ld;m.Sphere=Da;m.Ray=lb;m.Matrix4=K;m.Matrix3=ra;m.Box3=Oa;m.Box2=kd;m.Line3=Mb;m.Euler=Ya;m.Vector4=da;m.Vector3=p;m.Vector2=C;m.Quaternion=Z;m.Color=H;m.ImmediateRenderObject=ad;m.VertexNormalsHelper=bd;m.SpotLightHelper=nc;m.SkeletonHelper=oc;m.PointLightHelper=pc;m.RectAreaLightHelper=qc;m.HemisphereLightHelper=rc;m.GridHelper=cd;m.PolarGridHelper=
16832 Kd;m.FaceNormalsHelper=dd;m.DirectionalLightHelper=sc;m.CameraHelper=ed;m.BoxHelper=Db;m.Box3Helper=fd;m.PlaneHelper=gd;m.ArrowHelper=Eb;m.AxesHelper=hd;m.CatmullRomCurve3=ya;m.CubicBezierCurve3=Fb;m.QuadraticBezierCurve3=Gb;m.LineCurve3=db;m.ArcCurve=id;m.EllipseCurve=Na;m.SplineCurve=ab;m.CubicBezierCurve=bb;m.QuadraticBezierCurve=cb;m.LineCurve=Ka;m.Shape=Cb;m.Path=Bb;m.ShapePath=ce;m.Font=de;m.CurvePath=Ab;m.Curve=S;m.ShapeUtils=Ha;m.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=
16833 new Fc,d=0,e=b.length;d<e;d++)c.add(new pa(a,b[d]));return c},detach:function(a,b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},attach:function(a,b,c){a.applyMatrix((new K).getInverse(c.matrixWorld));b.remove(a);c.add(a)}};m.WebGLUtils=Pe;m.WireframeGeometry=Sb;m.ParametricGeometry=Hc;m.ParametricBufferGeometry=Tb;m.TetrahedronGeometry=Jc;m.TetrahedronBufferGeometry=Ub;m.OctahedronGeometry=Kc;m.OctahedronBufferGeometry=nb;m.IcosahedronGeometry=Lc;m.IcosahedronBufferGeometry=Vb;m.DodecahedronGeometry=
16834 Mc;m.DodecahedronBufferGeometry=Wb;m.PolyhedronGeometry=Ic;m.PolyhedronBufferGeometry=qa;m.TubeGeometry=Nc;m.TubeBufferGeometry=Xb;m.TorusKnotGeometry=Oc;m.TorusKnotBufferGeometry=Yb;m.TorusGeometry=Pc;m.TorusBufferGeometry=Zb;m.TextGeometry=Qc;m.TextBufferGeometry=$b;m.SphereGeometry=Rc;m.SphereBufferGeometry=ob;m.RingGeometry=Sc;m.RingBufferGeometry=ac;m.PlaneGeometry=Ac;m.PlaneBufferGeometry=kb;m.LatheGeometry=Tc;m.LatheBufferGeometry=bc;m.ShapeGeometry=cc;m.ShapeBufferGeometry=dc;m.ExtrudeGeometry=
16835 $a;m.ExtrudeBufferGeometry=Ga;m.EdgesGeometry=ec;m.ConeGeometry=Uc;m.ConeBufferGeometry=Vc;m.CylinderGeometry=pb;m.CylinderBufferGeometry=Sa;m.CircleGeometry=Wc;m.CircleBufferGeometry=fc;m.BoxGeometry=Lb;m.BoxBufferGeometry=jb;m.ShadowMaterial=gc;m.SpriteMaterial=Za;m.RawShaderMaterial=hc;m.ShaderMaterial=oa;m.PointsMaterial=Ba;m.MeshPhysicalMaterial=qb;m.MeshStandardMaterial=Ma;m.MeshPhongMaterial=Ia;m.MeshToonMaterial=rb;m.MeshNormalMaterial=sb;m.MeshLambertMaterial=tb;m.MeshDepthMaterial=Wa;m.MeshDistanceMaterial=
16836 Xa;m.MeshBasicMaterial=va;m.LineDashedMaterial=ub;m.LineBasicMaterial=O;m.Material=Q;m.Float64BufferAttribute=zc;m.Float32BufferAttribute=y;m.Uint32BufferAttribute=ib;m.Int32BufferAttribute=yc;m.Uint16BufferAttribute=hb;m.Int16BufferAttribute=xc;m.Uint8ClampedBufferAttribute=wc;m.Uint8BufferAttribute=vc;m.Int8BufferAttribute=uc;m.BufferAttribute=P;m.REVISION="88";m.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};m.CullFaceNone=0;m.CullFaceBack=1;m.CullFaceFront=2;m.CullFaceFrontBack=3;m.FrontFaceDirectionCW=0;m.FrontFaceDirectionCCW=
16837 1;m.BasicShadowMap=0;m.PCFShadowMap=1;m.PCFSoftShadowMap=2;m.FrontSide=0;m.BackSide=1;m.DoubleSide=2;m.FlatShading=1;m.SmoothShading=2;m.NoColors=0;m.FaceColors=1;m.VertexColors=2;m.NoBlending=0;m.NormalBlending=1;m.AdditiveBlending=2;m.SubtractiveBlending=3;m.MultiplyBlending=4;m.CustomBlending=5;m.AddEquation=100;m.SubtractEquation=101;m.ReverseSubtractEquation=102;m.MinEquation=103;m.MaxEquation=104;m.ZeroFactor=200;m.OneFactor=201;m.SrcColorFactor=202;m.OneMinusSrcColorFactor=203;m.SrcAlphaFactor=
16838 204;m.OneMinusSrcAlphaFactor=205;m.DstAlphaFactor=206;m.OneMinusDstAlphaFactor=207;m.DstColorFactor=208;m.OneMinusDstColorFactor=209;m.SrcAlphaSaturateFactor=210;m.NeverDepth=0;m.AlwaysDepth=1;m.LessDepth=2;m.LessEqualDepth=3;m.EqualDepth=4;m.GreaterEqualDepth=5;m.GreaterDepth=6;m.NotEqualDepth=7;m.MultiplyOperation=0;m.MixOperation=1;m.AddOperation=2;m.NoToneMapping=0;m.LinearToneMapping=1;m.ReinhardToneMapping=2;m.Uncharted2ToneMapping=3;m.CineonToneMapping=4;m.UVMapping=300;m.CubeReflectionMapping=
16839 301;m.CubeRefractionMapping=302;m.EquirectangularReflectionMapping=303;m.EquirectangularRefractionMapping=304;m.SphericalReflectionMapping=305;m.CubeUVReflectionMapping=306;m.CubeUVRefractionMapping=307;m.RepeatWrapping=1E3;m.ClampToEdgeWrapping=1001;m.MirroredRepeatWrapping=1002;m.NearestFilter=1003;m.NearestMipMapNearestFilter=1004;m.NearestMipMapLinearFilter=1005;m.LinearFilter=1006;m.LinearMipMapNearestFilter=1007;m.LinearMipMapLinearFilter=1008;m.UnsignedByteType=1009;m.ByteType=1010;m.ShortType=
16840 1011;m.UnsignedShortType=1012;m.IntType=1013;m.UnsignedIntType=1014;m.FloatType=1015;m.HalfFloatType=1016;m.UnsignedShort4444Type=1017;m.UnsignedShort5551Type=1018;m.UnsignedShort565Type=1019;m.UnsignedInt248Type=1020;m.AlphaFormat=1021;m.RGBFormat=1022;m.RGBAFormat=1023;m.LuminanceFormat=1024;m.LuminanceAlphaFormat=1025;m.RGBEFormat=1023;m.DepthFormat=1026;m.DepthStencilFormat=1027;m.RGB_S3TC_DXT1_Format=2001;m.RGBA_S3TC_DXT1_Format=2002;m.RGBA_S3TC_DXT3_Format=2003;m.RGBA_S3TC_DXT5_Format=2004;
16841 m.RGB_PVRTC_4BPPV1_Format=2100;m.RGB_PVRTC_2BPPV1_Format=2101;m.RGBA_PVRTC_4BPPV1_Format=2102;m.RGBA_PVRTC_2BPPV1_Format=2103;m.RGB_ETC1_Format=2151;m.LoopOnce=2200;m.LoopRepeat=2201;m.LoopPingPong=2202;m.InterpolateDiscrete=2300;m.InterpolateLinear=2301;m.InterpolateSmooth=2302;m.ZeroCurvatureEnding=2400;m.ZeroSlopeEnding=2401;m.WrapAroundEnding=2402;m.TrianglesDrawMode=0;m.TriangleStripDrawMode=1;m.TriangleFanDrawMode=2;m.LinearEncoding=3E3;m.sRGBEncoding=3001;m.GammaEncoding=3007;m.RGBEEncoding=
16842 3002;m.LogLuvEncoding=3003;m.RGBM7Encoding=3004;m.RGBM16Encoding=3005;m.RGBDEncoding=3006;m.BasicDepthPacking=3200;m.RGBADepthPacking=3201;m.CubeGeometry=Lb;m.Face4=function(a,b,c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new Pa(a,b,c,e,f,g)};m.LineStrip=0;m.LinePieces=1;m.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};m.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");
16843 a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};m.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Qb(a,b)};m.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new Cc(a)};m.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Qb(a,b)};m.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");
16844 return new Ba(a)};m.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Ba(a)};m.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Ba(a)};m.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new p(a,b,c)};m.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");
16845 return(new P(a,b)).setDynamic(!0)};m.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new uc(a,b)};m.Uint8Attribute=function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new vc(a,b)};m.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new wc(a,
16846 b)};m.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new xc(a,b)};m.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new hb(a,b)};m.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new yc(a,b)};m.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");
16847 return new ib(a,b)};m.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new y(a,b)};m.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new zc(a,b)};m.ClosedSplineCurve3=ef;m.SplineCurve3=ff;m.Spline=re;m.AxisHelper=function(a){console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper.");return new hd(a)};
16848 m.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new Db(a,b)};m.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new ca(new ec(a.geometry),new O({color:void 0!==b?b:16777215}))};m.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new ca(new Sb(a.geometry),new O({color:void 0!==
16849 b?b:16777215}))};m.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ja(a)};m.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new Zd(a)};m.GeometryUtils={merge:function(a,b,c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");if(b.isMesh){b.matrixAutoUpdate&&b.updateMatrix();
16850 var d=b.matrix;b=b.geometry}a.merge(b,d,c)},center:function(a){console.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.");return a.center()}};m.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");var e=new td;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");
16851 var e=new $d;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadCompressedTexture:function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")}};m.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=
16852 function(a,b){console.warn("THREE.Projector: .projectVector() is now vector.project().");a.project(b)};this.unprojectVector=function(a,b){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");a.unproject(b)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}};m.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml",
16853 "canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};Object.defineProperty(m,"__esModule",{value:!0})});
16855 },{}],232:[function(require,module,exports){
16858 module.exports = TinyQueue;
16860 function TinyQueue(data, compare) {
16861 if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
16863 this.data = data || [];
16864 this.length = this.data.length;
16865 this.compare = compare || defaultCompare;
16867 if (this.length > 0) {
16868 for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
16872 function defaultCompare(a, b) {
16873 return a < b ? -1 : a > b ? 1 : 0;
16876 TinyQueue.prototype = {
16878 push: function (item) {
16879 this.data.push(item);
16881 this._up(this.length - 1);
16885 if (this.length === 0) return undefined;
16886 var top = this.data[0];
16888 if (this.length > 0) {
16889 this.data[0] = this.data[this.length];
16896 peek: function () {
16897 return this.data[0];
16900 _up: function (pos) {
16901 var data = this.data;
16902 var compare = this.compare;
16903 var item = data[pos];
16906 var parent = (pos - 1) >> 1;
16907 var current = data[parent];
16908 if (compare(item, current) >= 0) break;
16909 data[pos] = current;
16916 _down: function (pos) {
16917 var data = this.data;
16918 var compare = this.compare;
16919 var len = this.length;
16920 var halfLen = len >> 1;
16921 var item = data[pos];
16923 while (pos < halfLen) {
16924 var left = (pos << 1) + 1;
16925 var right = left + 1;
16926 var best = data[left];
16928 if (right < len && compare(data[right], best) < 0) {
16930 best = data[right];
16932 if (compare(best, item) >= 0) break;
16942 },{}],233:[function(require,module,exports){
16943 // Underscore.js 1.8.3
16944 // http://underscorejs.org
16945 // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
16946 // Underscore may be freely distributed under the MIT license.
16953 // Establish the root object, `window` in the browser, or `exports` on the server.
16956 // Save the previous value of the `_` variable.
16957 var previousUnderscore = root._;
16959 // Save bytes in the minified (but not gzipped) version:
16960 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
16962 // Create quick reference variables for speed access to core prototypes.
16964 push = ArrayProto.push,
16965 slice = ArrayProto.slice,
16966 toString = ObjProto.toString,
16967 hasOwnProperty = ObjProto.hasOwnProperty;
16969 // All **ECMAScript 5** native function implementations that we hope to use
16970 // are declared here.
16972 nativeIsArray = Array.isArray,
16973 nativeKeys = Object.keys,
16974 nativeBind = FuncProto.bind,
16975 nativeCreate = Object.create;
16977 // Naked function reference for surrogate-prototype-swapping.
16978 var Ctor = function(){};
16980 // Create a safe reference to the Underscore object for use below.
16981 var _ = function(obj) {
16982 if (obj instanceof _) return obj;
16983 if (!(this instanceof _)) return new _(obj);
16984 this._wrapped = obj;
16987 // Export the Underscore object for **Node.js**, with
16988 // backwards-compatibility for the old `require()` API. If we're in
16989 // the browser, add `_` as a global object.
16990 if (typeof exports !== 'undefined') {
16991 if (typeof module !== 'undefined' && module.exports) {
16992 exports = module.exports = _;
16999 // Current version.
17000 _.VERSION = '1.8.3';
17002 // Internal function that returns an efficient (for current engines) version
17003 // of the passed-in callback, to be repeatedly applied in other Underscore
17005 var optimizeCb = function(func, context, argCount) {
17006 if (context === void 0) return func;
17007 switch (argCount == null ? 3 : argCount) {
17008 case 1: return function(value) {
17009 return func.call(context, value);
17011 case 2: return function(value, other) {
17012 return func.call(context, value, other);
17014 case 3: return function(value, index, collection) {
17015 return func.call(context, value, index, collection);
17017 case 4: return function(accumulator, value, index, collection) {
17018 return func.call(context, accumulator, value, index, collection);
17021 return function() {
17022 return func.apply(context, arguments);
17026 // A mostly-internal function to generate callbacks that can be applied
17027 // to each element in a collection, returning the desired result — either
17028 // identity, an arbitrary callback, a property matcher, or a property accessor.
17029 var cb = function(value, context, argCount) {
17030 if (value == null) return _.identity;
17031 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
17032 if (_.isObject(value)) return _.matcher(value);
17033 return _.property(value);
17035 _.iteratee = function(value, context) {
17036 return cb(value, context, Infinity);
17039 // An internal function for creating assigner functions.
17040 var createAssigner = function(keysFunc, undefinedOnly) {
17041 return function(obj) {
17042 var length = arguments.length;
17043 if (length < 2 || obj == null) return obj;
17044 for (var index = 1; index < length; index++) {
17045 var source = arguments[index],
17046 keys = keysFunc(source),
17048 for (var i = 0; i < l; i++) {
17050 if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
17057 // An internal function for creating a new object that inherits from another.
17058 var baseCreate = function(prototype) {
17059 if (!_.isObject(prototype)) return {};
17060 if (nativeCreate) return nativeCreate(prototype);
17061 Ctor.prototype = prototype;
17062 var result = new Ctor;
17063 Ctor.prototype = null;
17067 var property = function(key) {
17068 return function(obj) {
17069 return obj == null ? void 0 : obj[key];
17073 // Helper for collection methods to determine whether a collection
17074 // should be iterated as an array or as an object
17075 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
17076 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
17077 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
17078 var getLength = property('length');
17079 var isArrayLike = function(collection) {
17080 var length = getLength(collection);
17081 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
17084 // Collection Functions
17085 // --------------------
17087 // The cornerstone, an `each` implementation, aka `forEach`.
17088 // Handles raw objects in addition to array-likes. Treats all
17089 // sparse array-likes as if they were dense.
17090 _.each = _.forEach = function(obj, iteratee, context) {
17091 iteratee = optimizeCb(iteratee, context);
17093 if (isArrayLike(obj)) {
17094 for (i = 0, length = obj.length; i < length; i++) {
17095 iteratee(obj[i], i, obj);
17098 var keys = _.keys(obj);
17099 for (i = 0, length = keys.length; i < length; i++) {
17100 iteratee(obj[keys[i]], keys[i], obj);
17106 // Return the results of applying the iteratee to each element.
17107 _.map = _.collect = function(obj, iteratee, context) {
17108 iteratee = cb(iteratee, context);
17109 var keys = !isArrayLike(obj) && _.keys(obj),
17110 length = (keys || obj).length,
17111 results = Array(length);
17112 for (var index = 0; index < length; index++) {
17113 var currentKey = keys ? keys[index] : index;
17114 results[index] = iteratee(obj[currentKey], currentKey, obj);
17119 // Create a reducing function iterating left or right.
17120 function createReduce(dir) {
17121 // Optimized iterator function as using arguments.length
17122 // in the main function will deoptimize the, see #1991.
17123 function iterator(obj, iteratee, memo, keys, index, length) {
17124 for (; index >= 0 && index < length; index += dir) {
17125 var currentKey = keys ? keys[index] : index;
17126 memo = iteratee(memo, obj[currentKey], currentKey, obj);
17131 return function(obj, iteratee, memo, context) {
17132 iteratee = optimizeCb(iteratee, context, 4);
17133 var keys = !isArrayLike(obj) && _.keys(obj),
17134 length = (keys || obj).length,
17135 index = dir > 0 ? 0 : length - 1;
17136 // Determine the initial value if none is provided.
17137 if (arguments.length < 3) {
17138 memo = obj[keys ? keys[index] : index];
17141 return iterator(obj, iteratee, memo, keys, index, length);
17145 // **Reduce** builds up a single result from a list of values, aka `inject`,
17147 _.reduce = _.foldl = _.inject = createReduce(1);
17149 // The right-associative version of reduce, also known as `foldr`.
17150 _.reduceRight = _.foldr = createReduce(-1);
17152 // Return the first value which passes a truth test. Aliased as `detect`.
17153 _.find = _.detect = function(obj, predicate, context) {
17155 if (isArrayLike(obj)) {
17156 key = _.findIndex(obj, predicate, context);
17158 key = _.findKey(obj, predicate, context);
17160 if (key !== void 0 && key !== -1) return obj[key];
17163 // Return all the elements that pass a truth test.
17164 // Aliased as `select`.
17165 _.filter = _.select = function(obj, predicate, context) {
17167 predicate = cb(predicate, context);
17168 _.each(obj, function(value, index, list) {
17169 if (predicate(value, index, list)) results.push(value);
17174 // Return all the elements for which a truth test fails.
17175 _.reject = function(obj, predicate, context) {
17176 return _.filter(obj, _.negate(cb(predicate)), context);
17179 // Determine whether all of the elements match a truth test.
17180 // Aliased as `all`.
17181 _.every = _.all = function(obj, predicate, context) {
17182 predicate = cb(predicate, context);
17183 var keys = !isArrayLike(obj) && _.keys(obj),
17184 length = (keys || obj).length;
17185 for (var index = 0; index < length; index++) {
17186 var currentKey = keys ? keys[index] : index;
17187 if (!predicate(obj[currentKey], currentKey, obj)) return false;
17192 // Determine if at least one element in the object matches a truth test.
17193 // Aliased as `any`.
17194 _.some = _.any = function(obj, predicate, context) {
17195 predicate = cb(predicate, context);
17196 var keys = !isArrayLike(obj) && _.keys(obj),
17197 length = (keys || obj).length;
17198 for (var index = 0; index < length; index++) {
17199 var currentKey = keys ? keys[index] : index;
17200 if (predicate(obj[currentKey], currentKey, obj)) return true;
17205 // Determine if the array or object contains a given item (using `===`).
17206 // Aliased as `includes` and `include`.
17207 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
17208 if (!isArrayLike(obj)) obj = _.values(obj);
17209 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
17210 return _.indexOf(obj, item, fromIndex) >= 0;
17213 // Invoke a method (with arguments) on every item in a collection.
17214 _.invoke = function(obj, method) {
17215 var args = slice.call(arguments, 2);
17216 var isFunc = _.isFunction(method);
17217 return _.map(obj, function(value) {
17218 var func = isFunc ? method : value[method];
17219 return func == null ? func : func.apply(value, args);
17223 // Convenience version of a common use case of `map`: fetching a property.
17224 _.pluck = function(obj, key) {
17225 return _.map(obj, _.property(key));
17228 // Convenience version of a common use case of `filter`: selecting only objects
17229 // containing specific `key:value` pairs.
17230 _.where = function(obj, attrs) {
17231 return _.filter(obj, _.matcher(attrs));
17234 // Convenience version of a common use case of `find`: getting the first object
17235 // containing specific `key:value` pairs.
17236 _.findWhere = function(obj, attrs) {
17237 return _.find(obj, _.matcher(attrs));
17240 // Return the maximum element (or element-based computation).
17241 _.max = function(obj, iteratee, context) {
17242 var result = -Infinity, lastComputed = -Infinity,
17244 if (iteratee == null && obj != null) {
17245 obj = isArrayLike(obj) ? obj : _.values(obj);
17246 for (var i = 0, length = obj.length; i < length; i++) {
17248 if (value > result) {
17253 iteratee = cb(iteratee, context);
17254 _.each(obj, function(value, index, list) {
17255 computed = iteratee(value, index, list);
17256 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
17258 lastComputed = computed;
17265 // Return the minimum element (or element-based computation).
17266 _.min = function(obj, iteratee, context) {
17267 var result = Infinity, lastComputed = Infinity,
17269 if (iteratee == null && obj != null) {
17270 obj = isArrayLike(obj) ? obj : _.values(obj);
17271 for (var i = 0, length = obj.length; i < length; i++) {
17273 if (value < result) {
17278 iteratee = cb(iteratee, context);
17279 _.each(obj, function(value, index, list) {
17280 computed = iteratee(value, index, list);
17281 if (computed < lastComputed || computed === Infinity && result === Infinity) {
17283 lastComputed = computed;
17290 // Shuffle a collection, using the modern version of the
17291 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
17292 _.shuffle = function(obj) {
17293 var set = isArrayLike(obj) ? obj : _.values(obj);
17294 var length = set.length;
17295 var shuffled = Array(length);
17296 for (var index = 0, rand; index < length; index++) {
17297 rand = _.random(0, index);
17298 if (rand !== index) shuffled[index] = shuffled[rand];
17299 shuffled[rand] = set[index];
17304 // Sample **n** random values from a collection.
17305 // If **n** is not specified, returns a single random element.
17306 // The internal `guard` argument allows it to work with `map`.
17307 _.sample = function(obj, n, guard) {
17308 if (n == null || guard) {
17309 if (!isArrayLike(obj)) obj = _.values(obj);
17310 return obj[_.random(obj.length - 1)];
17312 return _.shuffle(obj).slice(0, Math.max(0, n));
17315 // Sort the object's values by a criterion produced by an iteratee.
17316 _.sortBy = function(obj, iteratee, context) {
17317 iteratee = cb(iteratee, context);
17318 return _.pluck(_.map(obj, function(value, index, list) {
17322 criteria: iteratee(value, index, list)
17324 }).sort(function(left, right) {
17325 var a = left.criteria;
17326 var b = right.criteria;
17328 if (a > b || a === void 0) return 1;
17329 if (a < b || b === void 0) return -1;
17331 return left.index - right.index;
17335 // An internal function used for aggregate "group by" operations.
17336 var group = function(behavior) {
17337 return function(obj, iteratee, context) {
17339 iteratee = cb(iteratee, context);
17340 _.each(obj, function(value, index) {
17341 var key = iteratee(value, index, obj);
17342 behavior(result, value, key);
17348 // Groups the object's values by a criterion. Pass either a string attribute
17349 // to group by, or a function that returns the criterion.
17350 _.groupBy = group(function(result, value, key) {
17351 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
17354 // Indexes the object's values by a criterion, similar to `groupBy`, but for
17355 // when you know that your index values will be unique.
17356 _.indexBy = group(function(result, value, key) {
17357 result[key] = value;
17360 // Counts instances of an object that group by a certain criterion. Pass
17361 // either a string attribute to count by, or a function that returns the
17363 _.countBy = group(function(result, value, key) {
17364 if (_.has(result, key)) result[key]++; else result[key] = 1;
17367 // Safely create a real, live array from anything iterable.
17368 _.toArray = function(obj) {
17369 if (!obj) return [];
17370 if (_.isArray(obj)) return slice.call(obj);
17371 if (isArrayLike(obj)) return _.map(obj, _.identity);
17372 return _.values(obj);
17375 // Return the number of elements in an object.
17376 _.size = function(obj) {
17377 if (obj == null) return 0;
17378 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
17381 // Split a collection into two arrays: one whose elements all satisfy the given
17382 // predicate, and one whose elements all do not satisfy the predicate.
17383 _.partition = function(obj, predicate, context) {
17384 predicate = cb(predicate, context);
17385 var pass = [], fail = [];
17386 _.each(obj, function(value, key, obj) {
17387 (predicate(value, key, obj) ? pass : fail).push(value);
17389 return [pass, fail];
17395 // Get the first element of an array. Passing **n** will return the first N
17396 // values in the array. Aliased as `head` and `take`. The **guard** check
17397 // allows it to work with `_.map`.
17398 _.first = _.head = _.take = function(array, n, guard) {
17399 if (array == null) return void 0;
17400 if (n == null || guard) return array[0];
17401 return _.initial(array, array.length - n);
17404 // Returns everything but the last entry of the array. Especially useful on
17405 // the arguments object. Passing **n** will return all the values in
17406 // the array, excluding the last N.
17407 _.initial = function(array, n, guard) {
17408 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
17411 // Get the last element of an array. Passing **n** will return the last N
17412 // values in the array.
17413 _.last = function(array, n, guard) {
17414 if (array == null) return void 0;
17415 if (n == null || guard) return array[array.length - 1];
17416 return _.rest(array, Math.max(0, array.length - n));
17419 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
17420 // Especially useful on the arguments object. Passing an **n** will return
17421 // the rest N values in the array.
17422 _.rest = _.tail = _.drop = function(array, n, guard) {
17423 return slice.call(array, n == null || guard ? 1 : n);
17426 // Trim out all falsy values from an array.
17427 _.compact = function(array) {
17428 return _.filter(array, _.identity);
17431 // Internal implementation of a recursive `flatten` function.
17432 var flatten = function(input, shallow, strict, startIndex) {
17433 var output = [], idx = 0;
17434 for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
17435 var value = input[i];
17436 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
17437 //flatten current level of array or arguments object
17438 if (!shallow) value = flatten(value, shallow, strict);
17439 var j = 0, len = value.length;
17440 output.length += len;
17442 output[idx++] = value[j++];
17444 } else if (!strict) {
17445 output[idx++] = value;
17451 // Flatten out an array, either recursively (by default), or just one level.
17452 _.flatten = function(array, shallow) {
17453 return flatten(array, shallow, false);
17456 // Return a version of the array that does not contain the specified value(s).
17457 _.without = function(array) {
17458 return _.difference(array, slice.call(arguments, 1));
17461 // Produce a duplicate-free version of the array. If the array has already
17462 // been sorted, you have the option of using a faster algorithm.
17463 // Aliased as `unique`.
17464 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
17465 if (!_.isBoolean(isSorted)) {
17466 context = iteratee;
17467 iteratee = isSorted;
17470 if (iteratee != null) iteratee = cb(iteratee, context);
17473 for (var i = 0, length = getLength(array); i < length; i++) {
17474 var value = array[i],
17475 computed = iteratee ? iteratee(value, i, array) : value;
17477 if (!i || seen !== computed) result.push(value);
17479 } else if (iteratee) {
17480 if (!_.contains(seen, computed)) {
17481 seen.push(computed);
17482 result.push(value);
17484 } else if (!_.contains(result, value)) {
17485 result.push(value);
17491 // Produce an array that contains the union: each distinct element from all of
17492 // the passed-in arrays.
17493 _.union = function() {
17494 return _.uniq(flatten(arguments, true, true));
17497 // Produce an array that contains every item shared between all the
17498 // passed-in arrays.
17499 _.intersection = function(array) {
17501 var argsLength = arguments.length;
17502 for (var i = 0, length = getLength(array); i < length; i++) {
17503 var item = array[i];
17504 if (_.contains(result, item)) continue;
17505 for (var j = 1; j < argsLength; j++) {
17506 if (!_.contains(arguments[j], item)) break;
17508 if (j === argsLength) result.push(item);
17513 // Take the difference between one array and a number of other arrays.
17514 // Only the elements present in just the first array will remain.
17515 _.difference = function(array) {
17516 var rest = flatten(arguments, true, true, 1);
17517 return _.filter(array, function(value){
17518 return !_.contains(rest, value);
17522 // Zip together multiple lists into a single array -- elements that share
17523 // an index go together.
17524 _.zip = function() {
17525 return _.unzip(arguments);
17528 // Complement of _.zip. Unzip accepts an array of arrays and groups
17529 // each array's elements on shared indices
17530 _.unzip = function(array) {
17531 var length = array && _.max(array, getLength).length || 0;
17532 var result = Array(length);
17534 for (var index = 0; index < length; index++) {
17535 result[index] = _.pluck(array, index);
17540 // Converts lists into objects. Pass either a single array of `[key, value]`
17541 // pairs, or two parallel arrays of the same length -- one of keys, and one of
17542 // the corresponding values.
17543 _.object = function(list, values) {
17545 for (var i = 0, length = getLength(list); i < length; i++) {
17547 result[list[i]] = values[i];
17549 result[list[i][0]] = list[i][1];
17555 // Generator function to create the findIndex and findLastIndex functions
17556 function createPredicateIndexFinder(dir) {
17557 return function(array, predicate, context) {
17558 predicate = cb(predicate, context);
17559 var length = getLength(array);
17560 var index = dir > 0 ? 0 : length - 1;
17561 for (; index >= 0 && index < length; index += dir) {
17562 if (predicate(array[index], index, array)) return index;
17568 // Returns the first index on an array-like that passes a predicate test
17569 _.findIndex = createPredicateIndexFinder(1);
17570 _.findLastIndex = createPredicateIndexFinder(-1);
17572 // Use a comparator function to figure out the smallest index at which
17573 // an object should be inserted so as to maintain order. Uses binary search.
17574 _.sortedIndex = function(array, obj, iteratee, context) {
17575 iteratee = cb(iteratee, context, 1);
17576 var value = iteratee(obj);
17577 var low = 0, high = getLength(array);
17578 while (low < high) {
17579 var mid = Math.floor((low + high) / 2);
17580 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
17585 // Generator function to create the indexOf and lastIndexOf functions
17586 function createIndexFinder(dir, predicateFind, sortedIndex) {
17587 return function(array, item, idx) {
17588 var i = 0, length = getLength(array);
17589 if (typeof idx == 'number') {
17591 i = idx >= 0 ? idx : Math.max(idx + length, i);
17593 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
17595 } else if (sortedIndex && idx && length) {
17596 idx = sortedIndex(array, item);
17597 return array[idx] === item ? idx : -1;
17599 if (item !== item) {
17600 idx = predicateFind(slice.call(array, i, length), _.isNaN);
17601 return idx >= 0 ? idx + i : -1;
17603 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
17604 if (array[idx] === item) return idx;
17610 // Return the position of the first occurrence of an item in an array,
17611 // or -1 if the item is not included in the array.
17612 // If the array is large and already in sort order, pass `true`
17613 // for **isSorted** to use binary search.
17614 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
17615 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
17617 // Generate an integer Array containing an arithmetic progression. A port of
17618 // the native Python `range()` function. See
17619 // [the Python documentation](http://docs.python.org/library/functions.html#range).
17620 _.range = function(start, stop, step) {
17621 if (stop == null) {
17627 var length = Math.max(Math.ceil((stop - start) / step), 0);
17628 var range = Array(length);
17630 for (var idx = 0; idx < length; idx++, start += step) {
17631 range[idx] = start;
17637 // Function (ahem) Functions
17638 // ------------------
17640 // Determines whether to execute a function as a constructor
17641 // or a normal function with the provided arguments
17642 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
17643 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
17644 var self = baseCreate(sourceFunc.prototype);
17645 var result = sourceFunc.apply(self, args);
17646 if (_.isObject(result)) return result;
17650 // Create a function bound to a given object (assigning `this`, and arguments,
17651 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
17653 _.bind = function(func, context) {
17654 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
17655 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
17656 var args = slice.call(arguments, 2);
17657 var bound = function() {
17658 return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
17663 // Partially apply a function by creating a version that has had some of its
17664 // arguments pre-filled, without changing its dynamic `this` context. _ acts
17665 // as a placeholder, allowing any combination of arguments to be pre-filled.
17666 _.partial = function(func) {
17667 var boundArgs = slice.call(arguments, 1);
17668 var bound = function() {
17669 var position = 0, length = boundArgs.length;
17670 var args = Array(length);
17671 for (var i = 0; i < length; i++) {
17672 args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
17674 while (position < arguments.length) args.push(arguments[position++]);
17675 return executeBound(func, bound, this, this, args);
17680 // Bind a number of an object's methods to that object. Remaining arguments
17681 // are the method names to be bound. Useful for ensuring that all callbacks
17682 // defined on an object belong to it.
17683 _.bindAll = function(obj) {
17684 var i, length = arguments.length, key;
17685 if (length <= 1) throw new Error('bindAll must be passed function names');
17686 for (i = 1; i < length; i++) {
17687 key = arguments[i];
17688 obj[key] = _.bind(obj[key], obj);
17693 // Memoize an expensive function by storing its results.
17694 _.memoize = function(func, hasher) {
17695 var memoize = function(key) {
17696 var cache = memoize.cache;
17697 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
17698 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
17699 return cache[address];
17701 memoize.cache = {};
17705 // Delays a function for the given number of milliseconds, and then calls
17706 // it with the arguments supplied.
17707 _.delay = function(func, wait) {
17708 var args = slice.call(arguments, 2);
17709 return setTimeout(function(){
17710 return func.apply(null, args);
17714 // Defers a function, scheduling it to run after the current call stack has
17716 _.defer = _.partial(_.delay, _, 1);
17718 // Returns a function, that, when invoked, will only be triggered at most once
17719 // during a given window of time. Normally, the throttled function will run
17720 // as much as it can, without ever going more than once per `wait` duration;
17721 // but if you'd like to disable the execution on the leading edge, pass
17722 // `{leading: false}`. To disable execution on the trailing edge, ditto.
17723 _.throttle = function(func, wait, options) {
17724 var context, args, result;
17725 var timeout = null;
17727 if (!options) options = {};
17728 var later = function() {
17729 previous = options.leading === false ? 0 : _.now();
17731 result = func.apply(context, args);
17732 if (!timeout) context = args = null;
17734 return function() {
17736 if (!previous && options.leading === false) previous = now;
17737 var remaining = wait - (now - previous);
17740 if (remaining <= 0 || remaining > wait) {
17742 clearTimeout(timeout);
17746 result = func.apply(context, args);
17747 if (!timeout) context = args = null;
17748 } else if (!timeout && options.trailing !== false) {
17749 timeout = setTimeout(later, remaining);
17755 // Returns a function, that, as long as it continues to be invoked, will not
17756 // be triggered. The function will be called after it stops being called for
17757 // N milliseconds. If `immediate` is passed, trigger the function on the
17758 // leading edge, instead of the trailing.
17759 _.debounce = function(func, wait, immediate) {
17760 var timeout, args, context, timestamp, result;
17762 var later = function() {
17763 var last = _.now() - timestamp;
17765 if (last < wait && last >= 0) {
17766 timeout = setTimeout(later, wait - last);
17770 result = func.apply(context, args);
17771 if (!timeout) context = args = null;
17776 return function() {
17779 timestamp = _.now();
17780 var callNow = immediate && !timeout;
17781 if (!timeout) timeout = setTimeout(later, wait);
17783 result = func.apply(context, args);
17784 context = args = null;
17791 // Returns the first function passed as an argument to the second,
17792 // allowing you to adjust arguments, run code before and after, and
17793 // conditionally execute the original function.
17794 _.wrap = function(func, wrapper) {
17795 return _.partial(wrapper, func);
17798 // Returns a negated version of the passed-in predicate.
17799 _.negate = function(predicate) {
17800 return function() {
17801 return !predicate.apply(this, arguments);
17805 // Returns a function that is the composition of a list of functions, each
17806 // consuming the return value of the function that follows.
17807 _.compose = function() {
17808 var args = arguments;
17809 var start = args.length - 1;
17810 return function() {
17812 var result = args[start].apply(this, arguments);
17813 while (i--) result = args[i].call(this, result);
17818 // Returns a function that will only be executed on and after the Nth call.
17819 _.after = function(times, func) {
17820 return function() {
17822 return func.apply(this, arguments);
17827 // Returns a function that will only be executed up to (but not including) the Nth call.
17828 _.before = function(times, func) {
17830 return function() {
17832 memo = func.apply(this, arguments);
17834 if (times <= 1) func = null;
17839 // Returns a function that will be executed at most one time, no matter how
17840 // often you call it. Useful for lazy initialization.
17841 _.once = _.partial(_.before, 2);
17843 // Object Functions
17844 // ----------------
17846 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
17847 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
17848 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
17849 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
17851 function collectNonEnumProps(obj, keys) {
17852 var nonEnumIdx = nonEnumerableProps.length;
17853 var constructor = obj.constructor;
17854 var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
17856 // Constructor is a special case.
17857 var prop = 'constructor';
17858 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
17860 while (nonEnumIdx--) {
17861 prop = nonEnumerableProps[nonEnumIdx];
17862 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
17868 // Retrieve the names of an object's own properties.
17869 // Delegates to **ECMAScript 5**'s native `Object.keys`
17870 _.keys = function(obj) {
17871 if (!_.isObject(obj)) return [];
17872 if (nativeKeys) return nativeKeys(obj);
17874 for (var key in obj) if (_.has(obj, key)) keys.push(key);
17876 if (hasEnumBug) collectNonEnumProps(obj, keys);
17880 // Retrieve all the property names of an object.
17881 _.allKeys = function(obj) {
17882 if (!_.isObject(obj)) return [];
17884 for (var key in obj) keys.push(key);
17886 if (hasEnumBug) collectNonEnumProps(obj, keys);
17890 // Retrieve the values of an object's properties.
17891 _.values = function(obj) {
17892 var keys = _.keys(obj);
17893 var length = keys.length;
17894 var values = Array(length);
17895 for (var i = 0; i < length; i++) {
17896 values[i] = obj[keys[i]];
17901 // Returns the results of applying the iteratee to each element of the object
17902 // In contrast to _.map it returns an object
17903 _.mapObject = function(obj, iteratee, context) {
17904 iteratee = cb(iteratee, context);
17905 var keys = _.keys(obj),
17906 length = keys.length,
17909 for (var index = 0; index < length; index++) {
17910 currentKey = keys[index];
17911 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
17916 // Convert an object into a list of `[key, value]` pairs.
17917 _.pairs = function(obj) {
17918 var keys = _.keys(obj);
17919 var length = keys.length;
17920 var pairs = Array(length);
17921 for (var i = 0; i < length; i++) {
17922 pairs[i] = [keys[i], obj[keys[i]]];
17927 // Invert the keys and values of an object. The values must be serializable.
17928 _.invert = function(obj) {
17930 var keys = _.keys(obj);
17931 for (var i = 0, length = keys.length; i < length; i++) {
17932 result[obj[keys[i]]] = keys[i];
17937 // Return a sorted list of the function names available on the object.
17938 // Aliased as `methods`
17939 _.functions = _.methods = function(obj) {
17941 for (var key in obj) {
17942 if (_.isFunction(obj[key])) names.push(key);
17944 return names.sort();
17947 // Extend a given object with all the properties in passed-in object(s).
17948 _.extend = createAssigner(_.allKeys);
17950 // Assigns a given object with all the own properties in the passed-in object(s)
17951 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
17952 _.extendOwn = _.assign = createAssigner(_.keys);
17954 // Returns the first key on an object that passes a predicate test
17955 _.findKey = function(obj, predicate, context) {
17956 predicate = cb(predicate, context);
17957 var keys = _.keys(obj), key;
17958 for (var i = 0, length = keys.length; i < length; i++) {
17960 if (predicate(obj[key], key, obj)) return key;
17964 // Return a copy of the object only containing the whitelisted properties.
17965 _.pick = function(object, oiteratee, context) {
17966 var result = {}, obj = object, iteratee, keys;
17967 if (obj == null) return result;
17968 if (_.isFunction(oiteratee)) {
17969 keys = _.allKeys(obj);
17970 iteratee = optimizeCb(oiteratee, context);
17972 keys = flatten(arguments, false, false, 1);
17973 iteratee = function(value, key, obj) { return key in obj; };
17976 for (var i = 0, length = keys.length; i < length; i++) {
17978 var value = obj[key];
17979 if (iteratee(value, key, obj)) result[key] = value;
17984 // Return a copy of the object without the blacklisted properties.
17985 _.omit = function(obj, iteratee, context) {
17986 if (_.isFunction(iteratee)) {
17987 iteratee = _.negate(iteratee);
17989 var keys = _.map(flatten(arguments, false, false, 1), String);
17990 iteratee = function(value, key) {
17991 return !_.contains(keys, key);
17994 return _.pick(obj, iteratee, context);
17997 // Fill in a given object with default properties.
17998 _.defaults = createAssigner(_.allKeys, true);
18000 // Creates an object that inherits from the given prototype object.
18001 // If additional properties are provided then they will be added to the
18003 _.create = function(prototype, props) {
18004 var result = baseCreate(prototype);
18005 if (props) _.extendOwn(result, props);
18009 // Create a (shallow-cloned) duplicate of an object.
18010 _.clone = function(obj) {
18011 if (!_.isObject(obj)) return obj;
18012 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
18015 // Invokes interceptor with the obj, and then returns obj.
18016 // The primary purpose of this method is to "tap into" a method chain, in
18017 // order to perform operations on intermediate results within the chain.
18018 _.tap = function(obj, interceptor) {
18023 // Returns whether an object has a given set of `key:value` pairs.
18024 _.isMatch = function(object, attrs) {
18025 var keys = _.keys(attrs), length = keys.length;
18026 if (object == null) return !length;
18027 var obj = Object(object);
18028 for (var i = 0; i < length; i++) {
18030 if (attrs[key] !== obj[key] || !(key in obj)) return false;
18036 // Internal recursive comparison function for `isEqual`.
18037 var eq = function(a, b, aStack, bStack) {
18038 // Identical objects are equal. `0 === -0`, but they aren't identical.
18039 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
18040 if (a === b) return a !== 0 || 1 / a === 1 / b;
18041 // A strict comparison is necessary because `null == undefined`.
18042 if (a == null || b == null) return a === b;
18043 // Unwrap any wrapped objects.
18044 if (a instanceof _) a = a._wrapped;
18045 if (b instanceof _) b = b._wrapped;
18046 // Compare `[[Class]]` names.
18047 var className = toString.call(a);
18048 if (className !== toString.call(b)) return false;
18049 switch (className) {
18050 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
18051 case '[object RegExp]':
18052 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
18053 case '[object String]':
18054 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
18055 // equivalent to `new String("5")`.
18056 return '' + a === '' + b;
18057 case '[object Number]':
18058 // `NaN`s are equivalent, but non-reflexive.
18059 // Object(NaN) is equivalent to NaN
18060 if (+a !== +a) return +b !== +b;
18061 // An `egal` comparison is performed for other numeric values.
18062 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
18063 case '[object Date]':
18064 case '[object Boolean]':
18065 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
18066 // millisecond representations. Note that invalid dates with millisecond representations
18067 // of `NaN` are not equivalent.
18071 var areArrays = className === '[object Array]';
18073 if (typeof a != 'object' || typeof b != 'object') return false;
18075 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
18076 // from different frames are.
18077 var aCtor = a.constructor, bCtor = b.constructor;
18078 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
18079 _.isFunction(bCtor) && bCtor instanceof bCtor)
18080 && ('constructor' in a && 'constructor' in b)) {
18084 // Assume equality for cyclic structures. The algorithm for detecting cyclic
18085 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
18087 // Initializing stack of traversed objects.
18088 // It's done here since we only need them for objects and arrays comparison.
18089 aStack = aStack || [];
18090 bStack = bStack || [];
18091 var length = aStack.length;
18093 // Linear search. Performance is inversely proportional to the number of
18094 // unique nested structures.
18095 if (aStack[length] === a) return bStack[length] === b;
18098 // Add the first object to the stack of traversed objects.
18102 // Recursively compare objects and arrays.
18104 // Compare array lengths to determine if a deep comparison is necessary.
18106 if (length !== b.length) return false;
18107 // Deep compare the contents, ignoring non-numeric properties.
18109 if (!eq(a[length], b[length], aStack, bStack)) return false;
18112 // Deep compare objects.
18113 var keys = _.keys(a), key;
18114 length = keys.length;
18115 // Ensure that both objects contain the same number of properties before comparing deep equality.
18116 if (_.keys(b).length !== length) return false;
18118 // Deep compare each member
18119 key = keys[length];
18120 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
18123 // Remove the first object from the stack of traversed objects.
18129 // Perform a deep comparison to check if two objects are equal.
18130 _.isEqual = function(a, b) {
18134 // Is a given array, string, or object empty?
18135 // An "empty" object has no enumerable own-properties.
18136 _.isEmpty = function(obj) {
18137 if (obj == null) return true;
18138 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
18139 return _.keys(obj).length === 0;
18142 // Is a given value a DOM element?
18143 _.isElement = function(obj) {
18144 return !!(obj && obj.nodeType === 1);
18147 // Is a given value an array?
18148 // Delegates to ECMA5's native Array.isArray
18149 _.isArray = nativeIsArray || function(obj) {
18150 return toString.call(obj) === '[object Array]';
18153 // Is a given variable an object?
18154 _.isObject = function(obj) {
18155 var type = typeof obj;
18156 return type === 'function' || type === 'object' && !!obj;
18159 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
18160 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
18161 _['is' + name] = function(obj) {
18162 return toString.call(obj) === '[object ' + name + ']';
18166 // Define a fallback version of the method in browsers (ahem, IE < 9), where
18167 // there isn't any inspectable "Arguments" type.
18168 if (!_.isArguments(arguments)) {
18169 _.isArguments = function(obj) {
18170 return _.has(obj, 'callee');
18174 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
18175 // IE 11 (#1621), and in Safari 8 (#1929).
18176 if (typeof /./ != 'function' && typeof Int8Array != 'object') {
18177 _.isFunction = function(obj) {
18178 return typeof obj == 'function' || false;
18182 // Is a given object a finite number?
18183 _.isFinite = function(obj) {
18184 return isFinite(obj) && !isNaN(parseFloat(obj));
18187 // Is the given value `NaN`? (NaN is the only number which does not equal itself).
18188 _.isNaN = function(obj) {
18189 return _.isNumber(obj) && obj !== +obj;
18192 // Is a given value a boolean?
18193 _.isBoolean = function(obj) {
18194 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
18197 // Is a given value equal to null?
18198 _.isNull = function(obj) {
18199 return obj === null;
18202 // Is a given variable undefined?
18203 _.isUndefined = function(obj) {
18204 return obj === void 0;
18207 // Shortcut function for checking if an object has a given property directly
18208 // on itself (in other words, not on a prototype).
18209 _.has = function(obj, key) {
18210 return obj != null && hasOwnProperty.call(obj, key);
18213 // Utility Functions
18214 // -----------------
18216 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
18217 // previous owner. Returns a reference to the Underscore object.
18218 _.noConflict = function() {
18219 root._ = previousUnderscore;
18223 // Keep the identity function around for default iteratees.
18224 _.identity = function(value) {
18228 // Predicate-generating functions. Often useful outside of Underscore.
18229 _.constant = function(value) {
18230 return function() {
18235 _.noop = function(){};
18237 _.property = property;
18239 // Generates a function for a given object that returns a given property.
18240 _.propertyOf = function(obj) {
18241 return obj == null ? function(){} : function(key) {
18246 // Returns a predicate for checking whether an object has a given set of
18247 // `key:value` pairs.
18248 _.matcher = _.matches = function(attrs) {
18249 attrs = _.extendOwn({}, attrs);
18250 return function(obj) {
18251 return _.isMatch(obj, attrs);
18255 // Run a function **n** times.
18256 _.times = function(n, iteratee, context) {
18257 var accum = Array(Math.max(0, n));
18258 iteratee = optimizeCb(iteratee, context, 1);
18259 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
18263 // Return a random integer between min and max (inclusive).
18264 _.random = function(min, max) {
18269 return min + Math.floor(Math.random() * (max - min + 1));
18272 // A (possibly faster) way to get the current timestamp as an integer.
18273 _.now = Date.now || function() {
18274 return new Date().getTime();
18277 // List of HTML entities for escaping.
18286 var unescapeMap = _.invert(escapeMap);
18288 // Functions for escaping and unescaping strings to/from HTML interpolation.
18289 var createEscaper = function(map) {
18290 var escaper = function(match) {
18293 // Regexes for identifying a key that needs to be escaped
18294 var source = '(?:' + _.keys(map).join('|') + ')';
18295 var testRegexp = RegExp(source);
18296 var replaceRegexp = RegExp(source, 'g');
18297 return function(string) {
18298 string = string == null ? '' : '' + string;
18299 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
18302 _.escape = createEscaper(escapeMap);
18303 _.unescape = createEscaper(unescapeMap);
18305 // If the value of the named `property` is a function then invoke it with the
18306 // `object` as context; otherwise, return it.
18307 _.result = function(object, property, fallback) {
18308 var value = object == null ? void 0 : object[property];
18309 if (value === void 0) {
18312 return _.isFunction(value) ? value.call(object) : value;
18315 // Generate a unique integer id (unique within the entire client session).
18316 // Useful for temporary DOM ids.
18318 _.uniqueId = function(prefix) {
18319 var id = ++idCounter + '';
18320 return prefix ? prefix + id : id;
18323 // By default, Underscore uses ERB-style template delimiters, change the
18324 // following template settings to use alternative delimiters.
18325 _.templateSettings = {
18326 evaluate : /<%([\s\S]+?)%>/g,
18327 interpolate : /<%=([\s\S]+?)%>/g,
18328 escape : /<%-([\s\S]+?)%>/g
18331 // When customizing `templateSettings`, if you don't want to define an
18332 // interpolation, evaluation or escaping regex, we need one that is
18333 // guaranteed not to match.
18334 var noMatch = /(.)^/;
18336 // Certain characters need to be escaped so that they can be put into a
18347 var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
18349 var escapeChar = function(match) {
18350 return '\\' + escapes[match];
18353 // JavaScript micro-templating, similar to John Resig's implementation.
18354 // Underscore templating handles arbitrary delimiters, preserves whitespace,
18355 // and correctly escapes quotes within interpolated code.
18356 // NB: `oldSettings` only exists for backwards compatibility.
18357 _.template = function(text, settings, oldSettings) {
18358 if (!settings && oldSettings) settings = oldSettings;
18359 settings = _.defaults({}, settings, _.templateSettings);
18361 // Combine delimiters into one regular expression via alternation.
18362 var matcher = RegExp([
18363 (settings.escape || noMatch).source,
18364 (settings.interpolate || noMatch).source,
18365 (settings.evaluate || noMatch).source
18366 ].join('|') + '|$', 'g');
18368 // Compile the template source, escaping string literals appropriately.
18370 var source = "__p+='";
18371 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
18372 source += text.slice(index, offset).replace(escaper, escapeChar);
18373 index = offset + match.length;
18376 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
18377 } else if (interpolate) {
18378 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
18379 } else if (evaluate) {
18380 source += "';\n" + evaluate + "\n__p+='";
18383 // Adobe VMs need the match returned to produce the correct offest.
18388 // If a variable is not specified, place data values in local scope.
18389 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
18391 source = "var __t,__p='',__j=Array.prototype.join," +
18392 "print=function(){__p+=__j.call(arguments,'');};\n" +
18393 source + 'return __p;\n';
18396 var render = new Function(settings.variable || 'obj', '_', source);
18402 var template = function(data) {
18403 return render.call(this, data, _);
18406 // Provide the compiled source as a convenience for precompilation.
18407 var argument = settings.variable || 'obj';
18408 template.source = 'function(' + argument + '){\n' + source + '}';
18413 // Add a "chain" function. Start chaining a wrapped Underscore object.
18414 _.chain = function(obj) {
18415 var instance = _(obj);
18416 instance._chain = true;
18422 // If Underscore is called as a function, it returns a wrapped object that
18423 // can be used OO-style. This wrapper holds altered versions of all the
18424 // underscore functions. Wrapped objects may be chained.
18426 // Helper function to continue chaining intermediate results.
18427 var result = function(instance, obj) {
18428 return instance._chain ? _(obj).chain() : obj;
18431 // Add your own custom functions to the Underscore object.
18432 _.mixin = function(obj) {
18433 _.each(_.functions(obj), function(name) {
18434 var func = _[name] = obj[name];
18435 _.prototype[name] = function() {
18436 var args = [this._wrapped];
18437 push.apply(args, arguments);
18438 return result(this, func.apply(_, args));
18443 // Add all of the Underscore functions to the wrapper object.
18446 // Add all mutator Array functions to the wrapper.
18447 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
18448 var method = ArrayProto[name];
18449 _.prototype[name] = function() {
18450 var obj = this._wrapped;
18451 method.apply(obj, arguments);
18452 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
18453 return result(this, obj);
18457 // Add all accessor Array functions to the wrapper.
18458 _.each(['concat', 'join', 'slice'], function(name) {
18459 var method = ArrayProto[name];
18460 _.prototype[name] = function() {
18461 return result(this, method.apply(this._wrapped, arguments));
18465 // Extracts the result from a wrapped and chained object.
18466 _.prototype.value = function() {
18467 return this._wrapped;
18470 // Provide unwrapping proxy for some methods used in engine operations
18471 // such as arithmetic and JSON stringification.
18472 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
18474 _.prototype.toString = function() {
18475 return '' + this._wrapped;
18478 // AMD registration happens at the end for compatibility with AMD loaders
18479 // that may not enforce next-turn semantics on modules. Even though general
18480 // practice for AMD registration is to be anonymous, underscore registers
18481 // as a named module because, like jQuery, it is a base library that is
18482 // popular enough to be bundled in a third party lib, but not be part of
18483 // an AMD load request. Those cases could generate an error when an
18484 // anonymous define() is called outside of a loader request.
18485 if (typeof define === 'function' && define.amd) {
18486 define('underscore', [], function() {
18492 },{}],234:[function(require,module,exports){
18493 var createElement = require("./vdom/create-element.js")
18495 module.exports = createElement
18497 },{"./vdom/create-element.js":240}],235:[function(require,module,exports){
18498 var diff = require("./vtree/diff.js")
18500 module.exports = diff
18502 },{"./vtree/diff.js":260}],236:[function(require,module,exports){
18503 var h = require("./virtual-hyperscript/index.js")
18507 },{"./virtual-hyperscript/index.js":247}],237:[function(require,module,exports){
18508 var diff = require("./diff.js")
18509 var patch = require("./patch.js")
18510 var h = require("./h.js")
18511 var create = require("./create-element.js")
18512 var VNode = require('./vnode/vnode.js')
18513 var VText = require('./vnode/vtext.js')
18524 },{"./create-element.js":234,"./diff.js":235,"./h.js":236,"./patch.js":238,"./vnode/vnode.js":256,"./vnode/vtext.js":258}],238:[function(require,module,exports){
18525 var patch = require("./vdom/patch.js")
18527 module.exports = patch
18529 },{"./vdom/patch.js":243}],239:[function(require,module,exports){
18530 var isObject = require("is-object")
18531 var isHook = require("../vnode/is-vhook.js")
18533 module.exports = applyProperties
18535 function applyProperties(node, props, previous) {
18536 for (var propName in props) {
18537 var propValue = props[propName]
18539 if (propValue === undefined) {
18540 removeProperty(node, propName, propValue, previous);
18541 } else if (isHook(propValue)) {
18542 removeProperty(node, propName, propValue, previous)
18543 if (propValue.hook) {
18544 propValue.hook(node,
18546 previous ? previous[propName] : undefined)
18549 if (isObject(propValue)) {
18550 patchObject(node, props, previous, propName, propValue);
18552 node[propName] = propValue
18558 function removeProperty(node, propName, propValue, previous) {
18560 var previousValue = previous[propName]
18562 if (!isHook(previousValue)) {
18563 if (propName === "attributes") {
18564 for (var attrName in previousValue) {
18565 node.removeAttribute(attrName)
18567 } else if (propName === "style") {
18568 for (var i in previousValue) {
18571 } else if (typeof previousValue === "string") {
18572 node[propName] = ""
18574 node[propName] = null
18576 } else if (previousValue.unhook) {
18577 previousValue.unhook(node, propName, propValue)
18582 function patchObject(node, props, previous, propName, propValue) {
18583 var previousValue = previous ? previous[propName] : undefined
18586 if (propName === "attributes") {
18587 for (var attrName in propValue) {
18588 var attrValue = propValue[attrName]
18590 if (attrValue === undefined) {
18591 node.removeAttribute(attrName)
18593 node.setAttribute(attrName, attrValue)
18600 if(previousValue && isObject(previousValue) &&
18601 getPrototype(previousValue) !== getPrototype(propValue)) {
18602 node[propName] = propValue
18606 if (!isObject(node[propName])) {
18607 node[propName] = {}
18610 var replacer = propName === "style" ? "" : undefined
18612 for (var k in propValue) {
18613 var value = propValue[k]
18614 node[propName][k] = (value === undefined) ? replacer : value
18618 function getPrototype(value) {
18619 if (Object.getPrototypeOf) {
18620 return Object.getPrototypeOf(value)
18621 } else if (value.__proto__) {
18622 return value.__proto__
18623 } else if (value.constructor) {
18624 return value.constructor.prototype
18628 },{"../vnode/is-vhook.js":251,"is-object":20}],240:[function(require,module,exports){
18629 var document = require("global/document")
18631 var applyProperties = require("./apply-properties")
18633 var isVNode = require("../vnode/is-vnode.js")
18634 var isVText = require("../vnode/is-vtext.js")
18635 var isWidget = require("../vnode/is-widget.js")
18636 var handleThunk = require("../vnode/handle-thunk.js")
18638 module.exports = createElement
18640 function createElement(vnode, opts) {
18641 var doc = opts ? opts.document || document : document
18642 var warn = opts ? opts.warn : null
18644 vnode = handleThunk(vnode).a
18646 if (isWidget(vnode)) {
18647 return vnode.init()
18648 } else if (isVText(vnode)) {
18649 return doc.createTextNode(vnode.text)
18650 } else if (!isVNode(vnode)) {
18652 warn("Item is not a valid virtual dom node", vnode)
18657 var node = (vnode.namespace === null) ?
18658 doc.createElement(vnode.tagName) :
18659 doc.createElementNS(vnode.namespace, vnode.tagName)
18661 var props = vnode.properties
18662 applyProperties(node, props)
18664 var children = vnode.children
18666 for (var i = 0; i < children.length; i++) {
18667 var childNode = createElement(children[i], opts)
18669 node.appendChild(childNode)
18676 },{"../vnode/handle-thunk.js":249,"../vnode/is-vnode.js":252,"../vnode/is-vtext.js":253,"../vnode/is-widget.js":254,"./apply-properties":239,"global/document":16}],241:[function(require,module,exports){
18677 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
18678 // We don't want to read all of the DOM nodes in the tree so we use
18679 // the in-order tree indexing to eliminate recursion down certain branches.
18680 // We only recurse into a DOM node if we know that it contains a child of
18685 module.exports = domIndex
18687 function domIndex(rootNode, tree, indices, nodes) {
18688 if (!indices || indices.length === 0) {
18691 indices.sort(ascending)
18692 return recurse(rootNode, tree, indices, nodes, 0)
18696 function recurse(rootNode, tree, indices, nodes, rootIndex) {
18697 nodes = nodes || {}
18701 if (indexInRange(indices, rootIndex, rootIndex)) {
18702 nodes[rootIndex] = rootNode
18705 var vChildren = tree.children
18709 var childNodes = rootNode.childNodes
18711 for (var i = 0; i < tree.children.length; i++) {
18714 var vChild = vChildren[i] || noChild
18715 var nextIndex = rootIndex + (vChild.count || 0)
18717 // skip recursion down the tree if there are no nodes down here
18718 if (indexInRange(indices, rootIndex, nextIndex)) {
18719 recurse(childNodes[i], vChild, indices, nodes, rootIndex)
18722 rootIndex = nextIndex
18730 // Binary search for an index in the interval [left, right]
18731 function indexInRange(indices, left, right) {
18732 if (indices.length === 0) {
18737 var maxIndex = indices.length - 1
18741 while (minIndex <= maxIndex) {
18742 currentIndex = ((maxIndex + minIndex) / 2) >> 0
18743 currentItem = indices[currentIndex]
18745 if (minIndex === maxIndex) {
18746 return currentItem >= left && currentItem <= right
18747 } else if (currentItem < left) {
18748 minIndex = currentIndex + 1
18749 } else if (currentItem > right) {
18750 maxIndex = currentIndex - 1
18759 function ascending(a, b) {
18760 return a > b ? 1 : -1
18763 },{}],242:[function(require,module,exports){
18764 var applyProperties = require("./apply-properties")
18766 var isWidget = require("../vnode/is-widget.js")
18767 var VPatch = require("../vnode/vpatch.js")
18769 var updateWidget = require("./update-widget")
18771 module.exports = applyPatch
18773 function applyPatch(vpatch, domNode, renderOptions) {
18774 var type = vpatch.type
18775 var vNode = vpatch.vNode
18776 var patch = vpatch.patch
18779 case VPatch.REMOVE:
18780 return removeNode(domNode, vNode)
18781 case VPatch.INSERT:
18782 return insertNode(domNode, patch, renderOptions)
18784 return stringPatch(domNode, vNode, patch, renderOptions)
18785 case VPatch.WIDGET:
18786 return widgetPatch(domNode, vNode, patch, renderOptions)
18788 return vNodePatch(domNode, vNode, patch, renderOptions)
18790 reorderChildren(domNode, patch)
18793 applyProperties(domNode, patch, vNode.properties)
18796 return replaceRoot(domNode,
18797 renderOptions.patch(domNode, patch, renderOptions))
18803 function removeNode(domNode, vNode) {
18804 var parentNode = domNode.parentNode
18807 parentNode.removeChild(domNode)
18810 destroyWidget(domNode, vNode);
18815 function insertNode(parentNode, vNode, renderOptions) {
18816 var newNode = renderOptions.render(vNode, renderOptions)
18819 parentNode.appendChild(newNode)
18825 function stringPatch(domNode, leftVNode, vText, renderOptions) {
18828 if (domNode.nodeType === 3) {
18829 domNode.replaceData(0, domNode.length, vText.text)
18832 var parentNode = domNode.parentNode
18833 newNode = renderOptions.render(vText, renderOptions)
18835 if (parentNode && newNode !== domNode) {
18836 parentNode.replaceChild(newNode, domNode)
18843 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
18844 var updating = updateWidget(leftVNode, widget)
18848 newNode = widget.update(leftVNode, domNode) || domNode
18850 newNode = renderOptions.render(widget, renderOptions)
18853 var parentNode = domNode.parentNode
18855 if (parentNode && newNode !== domNode) {
18856 parentNode.replaceChild(newNode, domNode)
18860 destroyWidget(domNode, leftVNode)
18866 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
18867 var parentNode = domNode.parentNode
18868 var newNode = renderOptions.render(vNode, renderOptions)
18870 if (parentNode && newNode !== domNode) {
18871 parentNode.replaceChild(newNode, domNode)
18877 function destroyWidget(domNode, w) {
18878 if (typeof w.destroy === "function" && isWidget(w)) {
18883 function reorderChildren(domNode, moves) {
18884 var childNodes = domNode.childNodes
18890 for (var i = 0; i < moves.removes.length; i++) {
18891 remove = moves.removes[i]
18892 node = childNodes[remove.from]
18894 keyMap[remove.key] = node
18896 domNode.removeChild(node)
18899 var length = childNodes.length
18900 for (var j = 0; j < moves.inserts.length; j++) {
18901 insert = moves.inserts[j]
18902 node = keyMap[insert.key]
18903 // this is the weirdest bug i've ever seen in webkit
18904 domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
18908 function replaceRoot(oldRoot, newRoot) {
18909 if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
18910 oldRoot.parentNode.replaceChild(newRoot, oldRoot)
18916 },{"../vnode/is-widget.js":254,"../vnode/vpatch.js":257,"./apply-properties":239,"./update-widget":244}],243:[function(require,module,exports){
18917 var document = require("global/document")
18918 var isArray = require("x-is-array")
18920 var render = require("./create-element")
18921 var domIndex = require("./dom-index")
18922 var patchOp = require("./patch-op")
18923 module.exports = patch
18925 function patch(rootNode, patches, renderOptions) {
18926 renderOptions = renderOptions || {}
18927 renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
18928 ? renderOptions.patch
18930 renderOptions.render = renderOptions.render || render
18932 return renderOptions.patch(rootNode, patches, renderOptions)
18935 function patchRecursive(rootNode, patches, renderOptions) {
18936 var indices = patchIndices(patches)
18938 if (indices.length === 0) {
18942 var index = domIndex(rootNode, patches.a, indices)
18943 var ownerDocument = rootNode.ownerDocument
18945 if (!renderOptions.document && ownerDocument !== document) {
18946 renderOptions.document = ownerDocument
18949 for (var i = 0; i < indices.length; i++) {
18950 var nodeIndex = indices[i]
18951 rootNode = applyPatch(rootNode,
18953 patches[nodeIndex],
18960 function applyPatch(rootNode, domNode, patchList, renderOptions) {
18967 if (isArray(patchList)) {
18968 for (var i = 0; i < patchList.length; i++) {
18969 newNode = patchOp(patchList[i], domNode, renderOptions)
18971 if (domNode === rootNode) {
18976 newNode = patchOp(patchList, domNode, renderOptions)
18978 if (domNode === rootNode) {
18986 function patchIndices(patches) {
18989 for (var key in patches) {
18991 indices.push(Number(key))
18998 },{"./create-element":240,"./dom-index":241,"./patch-op":242,"global/document":16,"x-is-array":279}],244:[function(require,module,exports){
18999 var isWidget = require("../vnode/is-widget.js")
19001 module.exports = updateWidget
19003 function updateWidget(a, b) {
19004 if (isWidget(a) && isWidget(b)) {
19005 if ("name" in a && "name" in b) {
19006 return a.id === b.id
19008 return a.init === b.init
19015 },{"../vnode/is-widget.js":254}],245:[function(require,module,exports){
19018 var EvStore = require('ev-store');
19020 module.exports = EvHook;
19022 function EvHook(value) {
19023 if (!(this instanceof EvHook)) {
19024 return new EvHook(value);
19027 this.value = value;
19030 EvHook.prototype.hook = function (node, propertyName) {
19031 var es = EvStore(node);
19032 var propName = propertyName.substr(3);
19034 es[propName] = this.value;
19037 EvHook.prototype.unhook = function(node, propertyName) {
19038 var es = EvStore(node);
19039 var propName = propertyName.substr(3);
19041 es[propName] = undefined;
19044 },{"ev-store":9}],246:[function(require,module,exports){
19047 module.exports = SoftSetHook;
19049 function SoftSetHook(value) {
19050 if (!(this instanceof SoftSetHook)) {
19051 return new SoftSetHook(value);
19054 this.value = value;
19057 SoftSetHook.prototype.hook = function (node, propertyName) {
19058 if (node[propertyName] !== this.value) {
19059 node[propertyName] = this.value;
19063 },{}],247:[function(require,module,exports){
19066 var isArray = require('x-is-array');
19068 var VNode = require('../vnode/vnode.js');
19069 var VText = require('../vnode/vtext.js');
19070 var isVNode = require('../vnode/is-vnode');
19071 var isVText = require('../vnode/is-vtext');
19072 var isWidget = require('../vnode/is-widget');
19073 var isHook = require('../vnode/is-vhook');
19074 var isVThunk = require('../vnode/is-thunk');
19076 var parseTag = require('./parse-tag.js');
19077 var softSetHook = require('./hooks/soft-set-hook.js');
19078 var evHook = require('./hooks/ev-hook.js');
19080 module.exports = h;
19082 function h(tagName, properties, children) {
19083 var childNodes = [];
19084 var tag, props, key, namespace;
19086 if (!children && isChildren(properties)) {
19087 children = properties;
19091 props = props || properties || {};
19092 tag = parseTag(tagName, props);
19095 if (props.hasOwnProperty('key')) {
19097 props.key = undefined;
19100 // support namespace
19101 if (props.hasOwnProperty('namespace')) {
19102 namespace = props.namespace;
19103 props.namespace = undefined;
19107 if (tag === 'INPUT' &&
19109 props.hasOwnProperty('value') &&
19110 props.value !== undefined &&
19111 !isHook(props.value)
19113 props.value = softSetHook(props.value);
19116 transformProperties(props);
19118 if (children !== undefined && children !== null) {
19119 addChild(children, childNodes, tag, props);
19123 return new VNode(tag, props, childNodes, key, namespace);
19126 function addChild(c, childNodes, tag, props) {
19127 if (typeof c === 'string') {
19128 childNodes.push(new VText(c));
19129 } else if (typeof c === 'number') {
19130 childNodes.push(new VText(String(c)));
19131 } else if (isChild(c)) {
19132 childNodes.push(c);
19133 } else if (isArray(c)) {
19134 for (var i = 0; i < c.length; i++) {
19135 addChild(c[i], childNodes, tag, props);
19137 } else if (c === null || c === undefined) {
19140 throw UnexpectedVirtualElement({
19150 function transformProperties(props) {
19151 for (var propName in props) {
19152 if (props.hasOwnProperty(propName)) {
19153 var value = props[propName];
19155 if (isHook(value)) {
19159 if (propName.substr(0, 3) === 'ev-') {
19160 // add ev-foo support
19161 props[propName] = evHook(value);
19167 function isChild(x) {
19168 return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
19171 function isChildren(x) {
19172 return typeof x === 'string' || isArray(x) || isChild(x);
19175 function UnexpectedVirtualElement(data) {
19176 var err = new Error();
19178 err.type = 'virtual-hyperscript.unexpected.virtual-element';
19179 err.message = 'Unexpected virtual child passed to h().\n' +
19180 'Expected a VNode / Vthunk / VWidget / string but:\n' +
19182 errorString(data.foreignObject) +
19184 'The parent vnode is:\n' +
19185 errorString(data.parentVnode)
19187 'Suggested fix: change your `h(..., [ ... ])` callsite.';
19188 err.foreignObject = data.foreignObject;
19189 err.parentVnode = data.parentVnode;
19194 function errorString(obj) {
19196 return JSON.stringify(obj, null, ' ');
19198 return String(obj);
19202 },{"../vnode/is-thunk":250,"../vnode/is-vhook":251,"../vnode/is-vnode":252,"../vnode/is-vtext":253,"../vnode/is-widget":254,"../vnode/vnode.js":256,"../vnode/vtext.js":258,"./hooks/ev-hook.js":245,"./hooks/soft-set-hook.js":246,"./parse-tag.js":248,"x-is-array":279}],248:[function(require,module,exports){
19205 var split = require('browser-split');
19207 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
19208 var notClassId = /^\.|#/;
19210 module.exports = parseTag;
19212 function parseTag(tag, props) {
19217 var noId = !(props.hasOwnProperty('id'));
19219 var tagParts = split(tag, classIdSplit);
19220 var tagName = null;
19222 if (notClassId.test(tagParts[1])) {
19226 var classes, part, type, i;
19228 for (i = 0; i < tagParts.length; i++) {
19229 part = tagParts[i];
19235 type = part.charAt(0);
19239 } else if (type === '.') {
19240 classes = classes || [];
19241 classes.push(part.substring(1, part.length));
19242 } else if (type === '#' && noId) {
19243 props.id = part.substring(1, part.length);
19248 if (props.className) {
19249 classes.push(props.className);
19252 props.className = classes.join(' ');
19255 return props.namespace ? tagName : tagName.toUpperCase();
19258 },{"browser-split":5}],249:[function(require,module,exports){
19259 var isVNode = require("./is-vnode")
19260 var isVText = require("./is-vtext")
19261 var isWidget = require("./is-widget")
19262 var isThunk = require("./is-thunk")
19264 module.exports = handleThunk
19266 function handleThunk(a, b) {
19271 renderedB = renderThunk(b, a)
19275 renderedA = renderThunk(a, null)
19284 function renderThunk(thunk, previous) {
19285 var renderedThunk = thunk.vnode
19287 if (!renderedThunk) {
19288 renderedThunk = thunk.vnode = thunk.render(previous)
19291 if (!(isVNode(renderedThunk) ||
19292 isVText(renderedThunk) ||
19293 isWidget(renderedThunk))) {
19294 throw new Error("thunk did not return a valid node");
19297 return renderedThunk
19300 },{"./is-thunk":250,"./is-vnode":252,"./is-vtext":253,"./is-widget":254}],250:[function(require,module,exports){
19301 module.exports = isThunk
19303 function isThunk(t) {
19304 return t && t.type === "Thunk"
19307 },{}],251:[function(require,module,exports){
19308 module.exports = isHook
19310 function isHook(hook) {
19312 (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
19313 typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
19316 },{}],252:[function(require,module,exports){
19317 var version = require("./version")
19319 module.exports = isVirtualNode
19321 function isVirtualNode(x) {
19322 return x && x.type === "VirtualNode" && x.version === version
19325 },{"./version":255}],253:[function(require,module,exports){
19326 var version = require("./version")
19328 module.exports = isVirtualText
19330 function isVirtualText(x) {
19331 return x && x.type === "VirtualText" && x.version === version
19334 },{"./version":255}],254:[function(require,module,exports){
19335 module.exports = isWidget
19337 function isWidget(w) {
19338 return w && w.type === "Widget"
19341 },{}],255:[function(require,module,exports){
19342 module.exports = "2"
19344 },{}],256:[function(require,module,exports){
19345 var version = require("./version")
19346 var isVNode = require("./is-vnode")
19347 var isWidget = require("./is-widget")
19348 var isThunk = require("./is-thunk")
19349 var isVHook = require("./is-vhook")
19351 module.exports = VirtualNode
19353 var noProperties = {}
19354 var noChildren = []
19356 function VirtualNode(tagName, properties, children, key, namespace) {
19357 this.tagName = tagName
19358 this.properties = properties || noProperties
19359 this.children = children || noChildren
19360 this.key = key != null ? String(key) : undefined
19361 this.namespace = (typeof namespace === "string") ? namespace : null
19363 var count = (children && children.length) || 0
19364 var descendants = 0
19365 var hasWidgets = false
19366 var hasThunks = false
19367 var descendantHooks = false
19370 for (var propName in properties) {
19371 if (properties.hasOwnProperty(propName)) {
19372 var property = properties[propName]
19373 if (isVHook(property) && property.unhook) {
19378 hooks[propName] = property
19383 for (var i = 0; i < count; i++) {
19384 var child = children[i]
19385 if (isVNode(child)) {
19386 descendants += child.count || 0
19388 if (!hasWidgets && child.hasWidgets) {
19392 if (!hasThunks && child.hasThunks) {
19396 if (!descendantHooks && (child.hooks || child.descendantHooks)) {
19397 descendantHooks = true
19399 } else if (!hasWidgets && isWidget(child)) {
19400 if (typeof child.destroy === "function") {
19403 } else if (!hasThunks && isThunk(child)) {
19408 this.count = count + descendants
19409 this.hasWidgets = hasWidgets
19410 this.hasThunks = hasThunks
19412 this.descendantHooks = descendantHooks
19415 VirtualNode.prototype.version = version
19416 VirtualNode.prototype.type = "VirtualNode"
19418 },{"./is-thunk":250,"./is-vhook":251,"./is-vnode":252,"./is-widget":254,"./version":255}],257:[function(require,module,exports){
19419 var version = require("./version")
19421 VirtualPatch.NONE = 0
19422 VirtualPatch.VTEXT = 1
19423 VirtualPatch.VNODE = 2
19424 VirtualPatch.WIDGET = 3
19425 VirtualPatch.PROPS = 4
19426 VirtualPatch.ORDER = 5
19427 VirtualPatch.INSERT = 6
19428 VirtualPatch.REMOVE = 7
19429 VirtualPatch.THUNK = 8
19431 module.exports = VirtualPatch
19433 function VirtualPatch(type, vNode, patch) {
19434 this.type = Number(type)
19439 VirtualPatch.prototype.version = version
19440 VirtualPatch.prototype.type = "VirtualPatch"
19442 },{"./version":255}],258:[function(require,module,exports){
19443 var version = require("./version")
19445 module.exports = VirtualText
19447 function VirtualText(text) {
19448 this.text = String(text)
19451 VirtualText.prototype.version = version
19452 VirtualText.prototype.type = "VirtualText"
19454 },{"./version":255}],259:[function(require,module,exports){
19455 var isObject = require("is-object")
19456 var isHook = require("../vnode/is-vhook")
19458 module.exports = diffProps
19460 function diffProps(a, b) {
19463 for (var aKey in a) {
19464 if (!(aKey in b)) {
19466 diff[aKey] = undefined
19469 var aValue = a[aKey]
19470 var bValue = b[aKey]
19472 if (aValue === bValue) {
19474 } else if (isObject(aValue) && isObject(bValue)) {
19475 if (getPrototype(bValue) !== getPrototype(aValue)) {
19477 diff[aKey] = bValue
19478 } else if (isHook(bValue)) {
19480 diff[aKey] = bValue
19482 var objectDiff = diffProps(aValue, bValue)
19485 diff[aKey] = objectDiff
19490 diff[aKey] = bValue
19494 for (var bKey in b) {
19495 if (!(bKey in a)) {
19497 diff[bKey] = b[bKey]
19504 function getPrototype(value) {
19505 if (Object.getPrototypeOf) {
19506 return Object.getPrototypeOf(value)
19507 } else if (value.__proto__) {
19508 return value.__proto__
19509 } else if (value.constructor) {
19510 return value.constructor.prototype
19514 },{"../vnode/is-vhook":251,"is-object":20}],260:[function(require,module,exports){
19515 var isArray = require("x-is-array")
19517 var VPatch = require("../vnode/vpatch")
19518 var isVNode = require("../vnode/is-vnode")
19519 var isVText = require("../vnode/is-vtext")
19520 var isWidget = require("../vnode/is-widget")
19521 var isThunk = require("../vnode/is-thunk")
19522 var handleThunk = require("../vnode/handle-thunk")
19524 var diffProps = require("./diff-props")
19526 module.exports = diff
19528 function diff(a, b) {
19529 var patch = { a: a }
19530 walk(a, b, patch, 0)
19534 function walk(a, b, patch, index) {
19539 var apply = patch[index]
19540 var applyClear = false
19542 if (isThunk(a) || isThunk(b)) {
19543 thunks(a, b, patch, index)
19544 } else if (b == null) {
19546 // If a is a widget we will add a remove patch for it
19547 // Otherwise any child widgets/hooks must be destroyed.
19548 // This prevents adding two remove patches for a widget.
19549 if (!isWidget(a)) {
19550 clearState(a, patch, index)
19551 apply = patch[index]
19554 apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
19555 } else if (isVNode(b)) {
19557 if (a.tagName === b.tagName &&
19558 a.namespace === b.namespace &&
19560 var propsPatch = diffProps(a.properties, b.properties)
19562 apply = appendPatch(apply,
19563 new VPatch(VPatch.PROPS, a, propsPatch))
19565 apply = diffChildren(a, b, patch, apply, index)
19567 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
19571 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
19574 } else if (isVText(b)) {
19576 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
19578 } else if (a.text !== b.text) {
19579 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
19581 } else if (isWidget(b)) {
19582 if (!isWidget(a)) {
19586 apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
19590 patch[index] = apply
19594 clearState(a, patch, index)
19598 function diffChildren(a, b, patch, apply, index) {
19599 var aChildren = a.children
19600 var orderedSet = reorder(aChildren, b.children)
19601 var bChildren = orderedSet.children
19603 var aLen = aChildren.length
19604 var bLen = bChildren.length
19605 var len = aLen > bLen ? aLen : bLen
19607 for (var i = 0; i < len; i++) {
19608 var leftNode = aChildren[i]
19609 var rightNode = bChildren[i]
19614 // Excess nodes in b need to be added
19615 apply = appendPatch(apply,
19616 new VPatch(VPatch.INSERT, null, rightNode))
19619 walk(leftNode, rightNode, patch, index)
19622 if (isVNode(leftNode) && leftNode.count) {
19623 index += leftNode.count
19627 if (orderedSet.moves) {
19628 // Reorder nodes last
19629 apply = appendPatch(apply, new VPatch(
19639 function clearState(vNode, patch, index) {
19640 // TODO: Make this a single walk, not two
19641 unhook(vNode, patch, index)
19642 destroyWidgets(vNode, patch, index)
19645 // Patch records for all destroyed widgets must be added because we need
19646 // a DOM node reference for the destroy function
19647 function destroyWidgets(vNode, patch, index) {
19648 if (isWidget(vNode)) {
19649 if (typeof vNode.destroy === "function") {
19650 patch[index] = appendPatch(
19652 new VPatch(VPatch.REMOVE, vNode, null)
19655 } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
19656 var children = vNode.children
19657 var len = children.length
19658 for (var i = 0; i < len; i++) {
19659 var child = children[i]
19662 destroyWidgets(child, patch, index)
19664 if (isVNode(child) && child.count) {
19665 index += child.count
19668 } else if (isThunk(vNode)) {
19669 thunks(vNode, null, patch, index)
19673 // Create a sub-patch for thunks
19674 function thunks(a, b, patch, index) {
19675 var nodes = handleThunk(a, b)
19676 var thunkPatch = diff(nodes.a, nodes.b)
19677 if (hasPatches(thunkPatch)) {
19678 patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
19682 function hasPatches(patch) {
19683 for (var index in patch) {
19684 if (index !== "a") {
19692 // Execute hooks when two nodes are identical
19693 function unhook(vNode, patch, index) {
19694 if (isVNode(vNode)) {
19696 patch[index] = appendPatch(
19701 undefinedKeys(vNode.hooks)
19706 if (vNode.descendantHooks || vNode.hasThunks) {
19707 var children = vNode.children
19708 var len = children.length
19709 for (var i = 0; i < len; i++) {
19710 var child = children[i]
19713 unhook(child, patch, index)
19715 if (isVNode(child) && child.count) {
19716 index += child.count
19720 } else if (isThunk(vNode)) {
19721 thunks(vNode, null, patch, index)
19725 function undefinedKeys(obj) {
19728 for (var key in obj) {
19729 result[key] = undefined
19735 // List diff, naive left to right reordering
19736 function reorder(aChildren, bChildren) {
19737 // O(M) time, O(M) memory
19738 var bChildIndex = keyIndex(bChildren)
19739 var bKeys = bChildIndex.keys
19740 var bFree = bChildIndex.free
19742 if (bFree.length === bChildren.length) {
19744 children: bChildren,
19749 // O(N) time, O(N) memory
19750 var aChildIndex = keyIndex(aChildren)
19751 var aKeys = aChildIndex.keys
19752 var aFree = aChildIndex.free
19754 if (aFree.length === aChildren.length) {
19756 children: bChildren,
19761 // O(MAX(N, M)) memory
19762 var newChildren = []
19765 var freeCount = bFree.length
19766 var deletedItems = 0
19768 // Iterate through a and match a node in b
19770 for (var i = 0 ; i < aChildren.length; i++) {
19771 var aItem = aChildren[i]
19775 if (bKeys.hasOwnProperty(aItem.key)) {
19776 // Match up the old keys
19777 itemIndex = bKeys[aItem.key]
19778 newChildren.push(bChildren[itemIndex])
19781 // Remove old keyed items
19782 itemIndex = i - deletedItems++
19783 newChildren.push(null)
19786 // Match the item in a with the next free item in b
19787 if (freeIndex < freeCount) {
19788 itemIndex = bFree[freeIndex++]
19789 newChildren.push(bChildren[itemIndex])
19791 // There are no free items in b to match with
19792 // the free items in a, so the extra free nodes
19794 itemIndex = i - deletedItems++
19795 newChildren.push(null)
19800 var lastFreeIndex = freeIndex >= bFree.length ?
19804 // Iterate through b and append any new keys
19806 for (var j = 0; j < bChildren.length; j++) {
19807 var newItem = bChildren[j]
19810 if (!aKeys.hasOwnProperty(newItem.key)) {
19811 // Add any new keyed items
19812 // We are adding new items to the end and then sorting them
19813 // in place. In future we should insert new items in place.
19814 newChildren.push(newItem)
19816 } else if (j >= lastFreeIndex) {
19817 // Add any leftover non-keyed items
19818 newChildren.push(newItem)
19822 var simulate = newChildren.slice()
19823 var simulateIndex = 0
19828 for (var k = 0; k < bChildren.length;) {
19829 var wantedItem = bChildren[k]
19830 simulateItem = simulate[simulateIndex]
19833 while (simulateItem === null && simulate.length) {
19834 removes.push(remove(simulate, simulateIndex, null))
19835 simulateItem = simulate[simulateIndex]
19838 if (!simulateItem || simulateItem.key !== wantedItem.key) {
19839 // if we need a key in this position...
19840 if (wantedItem.key) {
19841 if (simulateItem && simulateItem.key) {
19842 // if an insert doesn't put this key in place, it needs to move
19843 if (bKeys[simulateItem.key] !== k + 1) {
19844 removes.push(remove(simulate, simulateIndex, simulateItem.key))
19845 simulateItem = simulate[simulateIndex]
19846 // if the remove didn't put the wanted item in place, we need to insert it
19847 if (!simulateItem || simulateItem.key !== wantedItem.key) {
19848 inserts.push({key: wantedItem.key, to: k})
19850 // items are matching, so skip ahead
19856 inserts.push({key: wantedItem.key, to: k})
19860 inserts.push({key: wantedItem.key, to: k})
19864 // a key in simulate has no matching wanted key, remove it
19865 else if (simulateItem && simulateItem.key) {
19866 removes.push(remove(simulate, simulateIndex, simulateItem.key))
19875 // remove all the remaining nodes from simulate
19876 while(simulateIndex < simulate.length) {
19877 simulateItem = simulate[simulateIndex]
19878 removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
19881 // If the only moves we have are deletes then we can just
19882 // let the delete patch remove these items.
19883 if (removes.length === deletedItems && !inserts.length) {
19885 children: newChildren,
19891 children: newChildren,
19899 function remove(arr, index, key) {
19900 arr.splice(index, 1)
19908 function keyIndex(children) {
19911 var length = children.length
19913 for (var i = 0; i < length; i++) {
19914 var child = children[i]
19917 keys[child.key] = i
19924 keys: keys, // A hash of key name to index
19925 free: free // An array of unkeyed item indices
19929 function appendPatch(apply, patch) {
19931 if (isArray(apply)) {
19934 apply = [apply, patch]
19943 },{"../vnode/handle-thunk":249,"../vnode/is-thunk":250,"../vnode/is-vnode":252,"../vnode/is-vtext":253,"../vnode/is-widget":254,"../vnode/vpatch":257,"./diff-props":259,"x-is-array":279}],261:[function(require,module,exports){
19944 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19945 /** @author Brian Cavalier */
19946 /** @author John Hann */
19948 (function(define) { 'use strict';
19949 define(function (require) {
19951 var makePromise = require('./makePromise');
19952 var Scheduler = require('./Scheduler');
19953 var async = require('./env').asap;
19955 return makePromise({
19956 scheduler: new Scheduler(async)
19960 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
19962 },{"./Scheduler":262,"./env":274,"./makePromise":276}],262:[function(require,module,exports){
19963 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19964 /** @author Brian Cavalier */
19965 /** @author John Hann */
19967 (function(define) { 'use strict';
19968 define(function() {
19970 // Credit to Twisol (https://github.com/Twisol) for suggesting
19971 // this type of extensible queue + trampoline approach for next-tick conflation.
19974 * Async task scheduler
19975 * @param {function} async function to schedule a single async function
19978 function Scheduler(async) {
19979 this._async = async;
19980 this._running = false;
19982 this._queue = this;
19983 this._queueLen = 0;
19984 this._afterQueue = {};
19985 this._afterQueueLen = 0;
19988 this.drain = function() {
19995 * @param {{ run:function }} task
19997 Scheduler.prototype.enqueue = function(task) {
19998 this._queue[this._queueLen++] = task;
20003 * Enqueue a task to run after the main task queue
20004 * @param {{ run:function }} task
20006 Scheduler.prototype.afterQueue = function(task) {
20007 this._afterQueue[this._afterQueueLen++] = task;
20011 Scheduler.prototype.run = function() {
20012 if (!this._running) {
20013 this._running = true;
20014 this._async(this.drain);
20019 * Drain the handler queue entirely, and then the after queue
20021 Scheduler.prototype._drain = function() {
20023 for (; i < this._queueLen; ++i) {
20024 this._queue[i].run();
20025 this._queue[i] = void 0;
20028 this._queueLen = 0;
20029 this._running = false;
20031 for (i = 0; i < this._afterQueueLen; ++i) {
20032 this._afterQueue[i].run();
20033 this._afterQueue[i] = void 0;
20036 this._afterQueueLen = 0;
20042 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20044 },{}],263:[function(require,module,exports){
20045 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20046 /** @author Brian Cavalier */
20047 /** @author John Hann */
20049 (function(define) { 'use strict';
20050 define(function() {
20053 * Custom error type for promises rejected by promise.timeout
20054 * @param {string} message
20057 function TimeoutError (message) {
20059 this.message = message;
20060 this.name = TimeoutError.name;
20061 if (typeof Error.captureStackTrace === 'function') {
20062 Error.captureStackTrace(this, TimeoutError);
20066 TimeoutError.prototype = Object.create(Error.prototype);
20067 TimeoutError.prototype.constructor = TimeoutError;
20069 return TimeoutError;
20071 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20072 },{}],264:[function(require,module,exports){
20073 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20074 /** @author Brian Cavalier */
20075 /** @author John Hann */
20077 (function(define) { 'use strict';
20078 define(function() {
20080 makeApply.tryCatchResolve = tryCatchResolve;
20084 function makeApply(Promise, call) {
20085 if(arguments.length < 2) {
20086 call = tryCatchResolve;
20091 function apply(f, thisArg, args) {
20092 var p = Promise._defer();
20093 var l = args.length;
20094 var params = new Array(l);
20095 callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
20100 function callAndResolve(c, h) {
20102 return call(c.f, c.thisArg, c.params, h);
20105 var handler = Promise._handler(c.args[c.i]);
20106 handler.fold(callAndResolveNext, c, void 0, h);
20109 function callAndResolveNext(c, x, h) {
20112 callAndResolve(c, h);
20116 function tryCatchResolve(f, thisArg, args, resolver) {
20118 resolver.resolve(f.apply(thisArg, args));
20120 resolver.reject(e);
20125 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20129 },{}],265:[function(require,module,exports){
20130 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20131 /** @author Brian Cavalier */
20132 /** @author John Hann */
20134 (function(define) { 'use strict';
20135 define(function(require) {
20137 var state = require('../state');
20138 var applier = require('../apply');
20140 return function array(Promise) {
20142 var applyFold = applier(Promise);
20143 var toPromise = Promise.resolve;
20144 var all = Promise.all;
20146 var ar = Array.prototype.reduce;
20147 var arr = Array.prototype.reduceRight;
20148 var slice = Array.prototype.slice;
20150 // Additional array combinators
20153 Promise.some = some;
20154 Promise.settle = settle;
20157 Promise.filter = filter;
20158 Promise.reduce = reduce;
20159 Promise.reduceRight = reduceRight;
20162 * When this promise fulfills with an array, do
20163 * onFulfilled.apply(void 0, array)
20164 * @param {function} onFulfilled function to apply
20165 * @returns {Promise} promise for the result of applying onFulfilled
20167 Promise.prototype.spread = function(onFulfilled) {
20168 return this.then(all).then(function(array) {
20169 return onFulfilled.apply(this, array);
20176 * One-winner competitive race.
20177 * Return a promise that will fulfill when one of the promises
20178 * in the input array fulfills, or will reject when all promises
20180 * @param {array} promises
20181 * @returns {Promise} promise for the first fulfilled value
20183 function any(promises) {
20184 var p = Promise._defer();
20185 var resolver = p._handler;
20186 var l = promises.length>>>0;
20191 for (var h, x, i = 0; i < l; ++i) {
20193 if(x === void 0 && !(i in promises)) {
20198 h = Promise._handler(x);
20199 if(h.state() > 0) {
20200 resolver.become(h);
20201 Promise._visitRemaining(promises, i, h);
20204 h.visit(resolver, handleFulfill, handleReject);
20208 if(pending === 0) {
20209 resolver.reject(new RangeError('any(): array must not be empty'));
20214 function handleFulfill(x) {
20215 /*jshint validthis:true*/
20217 this.resolve(x); // this === resolver
20220 function handleReject(e) {
20221 /*jshint validthis:true*/
20222 if(this.resolved) { // this === resolver
20227 if(--pending === 0) {
20228 this.reject(errors);
20234 * N-winner competitive race
20235 * Return a promise that will fulfill when n input promises have
20236 * fulfilled, or will reject when it becomes impossible for n
20237 * input promises to fulfill (ie when promises.length - n + 1
20239 * @param {array} promises
20240 * @param {number} n
20241 * @returns {Promise} promise for the earliest n fulfillment values
20245 function some(promises, n) {
20246 /*jshint maxcomplexity:7*/
20247 var p = Promise._defer();
20248 var resolver = p._handler;
20253 var l = promises.length>>>0;
20256 var x, i; // reused in both for() loops
20258 // First pass: count actual array items
20259 for(i=0; i<l; ++i) {
20261 if(x === void 0 && !(i in promises)) {
20267 // Compute actual goals
20268 n = Math.max(n, 0);
20269 nReject = (nFulfill - n + 1);
20270 nFulfill = Math.min(n, nFulfill);
20273 resolver.reject(new RangeError('some(): array must contain at least '
20274 + n + ' item(s), but had ' + nFulfill));
20275 } else if(nFulfill === 0) {
20276 resolver.resolve(results);
20279 // Second pass: observe each array item, make progress toward goals
20280 for(i=0; i<l; ++i) {
20282 if(x === void 0 && !(i in promises)) {
20286 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
20291 function fulfill(x) {
20292 /*jshint validthis:true*/
20293 if(this.resolved) { // this === resolver
20298 if(--nFulfill === 0) {
20300 this.resolve(results);
20304 function reject(e) {
20305 /*jshint validthis:true*/
20306 if(this.resolved) { // this === resolver
20311 if(--nReject === 0) {
20313 this.reject(errors);
20319 * Apply f to the value of each promise in a list of promises
20320 * and return a new list containing the results.
20321 * @param {array} promises
20322 * @param {function(x:*, index:Number):*} f mapping function
20323 * @returns {Promise}
20325 function map(promises, f) {
20326 return Promise._traverse(f, promises);
20330 * Filter the provided array of promises using the provided predicate. Input may
20331 * contain promises and values
20332 * @param {Array} promises array of promises and values
20333 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
20334 * Must return truthy (or promise for truthy) for items to retain.
20335 * @returns {Promise} promise that will fulfill with an array containing all items
20336 * for which predicate returned truthy.
20338 function filter(promises, predicate) {
20339 var a = slice.call(promises);
20340 return Promise._traverse(predicate, a).then(function(keep) {
20341 return filterSync(a, keep);
20345 function filterSync(promises, keep) {
20346 // Safe because we know all promises have fulfilled if we've made it this far
20347 var l = keep.length;
20348 var filtered = new Array(l);
20349 for(var i=0, j=0; i<l; ++i) {
20351 filtered[j++] = Promise._handler(promises[i]).value;
20354 filtered.length = j;
20360 * Return a promise that will always fulfill with an array containing
20361 * the outcome states of all input promises. The returned promise
20362 * will never reject.
20363 * @param {Array} promises
20364 * @returns {Promise} promise for array of settled state descriptors
20366 function settle(promises) {
20367 return all(promises.map(settleOne));
20370 function settleOne(p) {
20371 // Optimize the case where we get an already-resolved when.js promise
20372 // by extracting its state:
20374 if (p instanceof Promise) {
20375 // This is our own Promise type and we can reach its handler internals:
20376 handler = p._handler.join();
20378 if((handler && handler.state() === 0) || !handler) {
20379 // Either still pending, or not a Promise at all:
20380 return toPromise(p).then(state.fulfilled, state.rejected);
20383 // The promise is our own, but it is already resolved. Take a shortcut.
20384 // Since we're not actually handling the resolution, we need to disable
20385 // rejection reporting.
20386 handler._unreport();
20387 return state.inspect(handler);
20391 * Traditional reduce function, similar to `Array.prototype.reduce()`, but
20392 * input may contain promises and/or values, and reduceFunc
20393 * may return either a value or a promise, *and* initialValue may
20394 * be a promise for the starting value.
20395 * @param {Array|Promise} promises array or promise for an array of anything,
20396 * may contain a mix of promises and values.
20397 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20398 * @returns {Promise} that will resolve to the final reduced value
20400 function reduce(promises, f /*, initialValue */) {
20401 return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
20402 : ar.call(promises, liftCombine(f));
20406 * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
20407 * input may contain promises and/or values, and reduceFunc
20408 * may return either a value or a promise, *and* initialValue may
20409 * be a promise for the starting value.
20410 * @param {Array|Promise} promises array or promise for an array of anything,
20411 * may contain a mix of promises and values.
20412 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20413 * @returns {Promise} that will resolve to the final reduced value
20415 function reduceRight(promises, f /*, initialValue */) {
20416 return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
20417 : arr.call(promises, liftCombine(f));
20420 function liftCombine(f) {
20421 return function(z, x, i) {
20422 return applyFold(f, void 0, [z,x,i]);
20428 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20430 },{"../apply":264,"../state":277}],266:[function(require,module,exports){
20431 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20432 /** @author Brian Cavalier */
20433 /** @author John Hann */
20435 (function(define) { 'use strict';
20436 define(function() {
20438 return function flow(Promise) {
20440 var resolve = Promise.resolve;
20441 var reject = Promise.reject;
20442 var origCatch = Promise.prototype['catch'];
20445 * Handle the ultimate fulfillment value or rejection reason, and assume
20446 * responsibility for all errors. If an error propagates out of result
20447 * or handleFatalError, it will be rethrown to the host, resulting in a
20448 * loud stack track on most platforms and a crash on some.
20449 * @param {function?} onResult
20450 * @param {function?} onError
20451 * @returns {undefined}
20453 Promise.prototype.done = function(onResult, onError) {
20454 this._handler.visit(this._handler.receiver, onResult, onError);
20458 * Add Error-type and predicate matching to catch. Examples:
20459 * promise.catch(TypeError, handleTypeError)
20460 * .catch(predicate, handleMatchedErrors)
20461 * .catch(handleRemainingErrors)
20462 * @param onRejected
20465 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
20466 if (arguments.length < 2) {
20467 return origCatch.call(this, onRejected);
20470 if(typeof onRejected !== 'function') {
20471 return this.ensure(rejectInvalidPredicate);
20474 return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
20478 * Wraps the provided catch handler, so that it will only be called
20479 * if the predicate evaluates truthy
20480 * @param {?function} handler
20481 * @param {function} predicate
20482 * @returns {function} conditional catch handler
20484 function createCatchFilter(handler, predicate) {
20485 return function(e) {
20486 return evaluatePredicate(e, predicate)
20487 ? handler.call(this, e)
20493 * Ensures that onFulfilledOrRejected will be called regardless of whether
20494 * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
20495 * receive the promises' value or reason. Any returned value will be disregarded.
20496 * onFulfilledOrRejected may throw or return a rejected promise to signal
20497 * an additional error.
20498 * @param {function} handler handler to be called regardless of
20499 * fulfillment or rejection
20500 * @returns {Promise}
20502 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
20503 if(typeof handler !== 'function') {
20507 return this.then(function(x) {
20508 return runSideEffect(handler, this, identity, x);
20510 return runSideEffect(handler, this, reject, e);
20514 function runSideEffect (handler, thisArg, propagate, value) {
20515 var result = handler.call(thisArg);
20516 return maybeThenable(result)
20517 ? propagateValue(result, propagate, value)
20518 : propagate(value);
20521 function propagateValue (result, propagate, x) {
20522 return resolve(result).then(function () {
20523 return propagate(x);
20528 * Recover from a failure by returning a defaultValue. If defaultValue
20529 * is a promise, it's fulfillment value will be used. If defaultValue is
20530 * a promise that rejects, the returned promise will reject with the
20532 * @param {*} defaultValue
20533 * @returns {Promise} new promise
20535 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
20536 return this.then(void 0, function() {
20537 return defaultValue;
20542 * Shortcut for .then(function() { return value; })
20544 * @return {Promise} a promise that:
20545 * - is fulfilled if value is not a promise, or
20546 * - if value is a promise, will fulfill with its value, or reject
20549 Promise.prototype['yield'] = function(value) {
20550 return this.then(function() {
20556 * Runs a side effect when this promise fulfills, without changing the
20557 * fulfillment value.
20558 * @param {function} onFulfilledSideEffect
20559 * @returns {Promise}
20561 Promise.prototype.tap = function(onFulfilledSideEffect) {
20562 return this.then(onFulfilledSideEffect)['yield'](this);
20568 function rejectInvalidPredicate() {
20569 throw new TypeError('catch predicate must be a function');
20572 function evaluatePredicate(e, predicate) {
20573 return isError(predicate) ? e instanceof predicate : predicate(e);
20576 function isError(predicate) {
20577 return predicate === Error
20578 || (predicate != null && predicate.prototype instanceof Error);
20581 function maybeThenable(x) {
20582 return (typeof x === 'object' || typeof x === 'function') && x !== null;
20585 function identity(x) {
20590 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20592 },{}],267:[function(require,module,exports){
20593 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20594 /** @author Brian Cavalier */
20595 /** @author John Hann */
20596 /** @author Jeff Escalante */
20598 (function(define) { 'use strict';
20599 define(function() {
20601 return function fold(Promise) {
20603 Promise.prototype.fold = function(f, z) {
20604 var promise = this._beget();
20606 this._handler.fold(function(z, x, to) {
20607 Promise._handler(z).fold(function(x, z, to) {
20608 to.resolve(f.call(this, z, x));
20610 }, z, promise._handler.receiver, promise._handler);
20619 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20621 },{}],268:[function(require,module,exports){
20622 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20623 /** @author Brian Cavalier */
20624 /** @author John Hann */
20626 (function(define) { 'use strict';
20627 define(function(require) {
20629 var inspect = require('../state').inspect;
20631 return function inspection(Promise) {
20633 Promise.prototype.inspect = function() {
20634 return inspect(Promise._handler(this));
20641 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20643 },{"../state":277}],269:[function(require,module,exports){
20644 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20645 /** @author Brian Cavalier */
20646 /** @author John Hann */
20648 (function(define) { 'use strict';
20649 define(function() {
20651 return function generate(Promise) {
20653 var resolve = Promise.resolve;
20655 Promise.iterate = iterate;
20656 Promise.unfold = unfold;
20661 * @deprecated Use github.com/cujojs/most streams and most.iterate
20662 * Generate a (potentially infinite) stream of promised values:
20663 * x, f(x), f(f(x)), etc. until condition(x) returns true
20664 * @param {function} f function to generate a new x from the previous x
20665 * @param {function} condition function that, given the current x, returns
20666 * truthy when the iterate should stop
20667 * @param {function} handler function to handle the value produced by f
20668 * @param {*|Promise} x starting value, may be a promise
20669 * @return {Promise} the result of the last call to f before
20670 * condition returns true
20672 function iterate(f, condition, handler, x) {
20673 return unfold(function(x) {
20675 }, condition, handler, x);
20679 * @deprecated Use github.com/cujojs/most streams and most.unfold
20680 * Generate a (potentially infinite) stream of promised values
20681 * by applying handler(generator(seed)) iteratively until
20682 * condition(seed) returns true.
20683 * @param {function} unspool function that generates a [value, newSeed]
20685 * @param {function} condition function that, given the current seed, returns
20686 * truthy when the unfold should stop
20687 * @param {function} handler function to handle the value produced by unspool
20688 * @param x {*|Promise} starting value, may be a promise
20689 * @return {Promise} the result of the last value produced by unspool before
20690 * condition returns true
20692 function unfold(unspool, condition, handler, x) {
20693 return resolve(x).then(function(seed) {
20694 return resolve(condition(seed)).then(function(done) {
20695 return done ? seed : resolve(unspool(seed)).spread(next);
20699 function next(item, newSeed) {
20700 return resolve(handler(item)).then(function() {
20701 return unfold(unspool, condition, handler, newSeed);
20708 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20710 },{}],270:[function(require,module,exports){
20711 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20712 /** @author Brian Cavalier */
20713 /** @author John Hann */
20715 (function(define) { 'use strict';
20716 define(function() {
20718 return function progress(Promise) {
20722 * Register a progress handler for this promise
20723 * @param {function} onProgress
20724 * @returns {Promise}
20726 Promise.prototype.progress = function(onProgress) {
20727 return this.then(void 0, void 0, onProgress);
20734 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20736 },{}],271:[function(require,module,exports){
20737 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20738 /** @author Brian Cavalier */
20739 /** @author John Hann */
20741 (function(define) { 'use strict';
20742 define(function(require) {
20744 var env = require('../env');
20745 var TimeoutError = require('../TimeoutError');
20747 function setTimeout(f, ms, x, y) {
20748 return env.setTimer(function() {
20753 return function timed(Promise) {
20755 * Return a new promise whose fulfillment value is revealed only
20756 * after ms milliseconds
20757 * @param {number} ms milliseconds
20758 * @returns {Promise}
20760 Promise.prototype.delay = function(ms) {
20761 var p = this._beget();
20762 this._handler.fold(handleDelay, ms, void 0, p._handler);
20766 function handleDelay(ms, x, h) {
20767 setTimeout(resolveDelay, ms, x, h);
20770 function resolveDelay(x, h) {
20775 * Return a new promise that rejects after ms milliseconds unless
20776 * this promise fulfills earlier, in which case the returned promise
20777 * fulfills with the same value.
20778 * @param {number} ms milliseconds
20779 * @param {Error|*=} reason optional rejection reason to use, defaults
20780 * to a TimeoutError if not provided
20781 * @returns {Promise}
20783 Promise.prototype.timeout = function(ms, reason) {
20784 var p = this._beget();
20785 var h = p._handler;
20787 var t = setTimeout(onTimeout, ms, reason, p._handler);
20789 this._handler.visit(h,
20790 function onFulfill(x) {
20792 this.resolve(x); // this = h
20794 function onReject(x) {
20796 this.reject(x); // this = h
20803 function onTimeout(reason, h, ms) {
20804 var e = typeof reason === 'undefined'
20805 ? new TimeoutError('timed out after ' + ms + 'ms')
20814 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20816 },{"../TimeoutError":263,"../env":274}],272:[function(require,module,exports){
20817 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20818 /** @author Brian Cavalier */
20819 /** @author John Hann */
20821 (function(define) { 'use strict';
20822 define(function(require) {
20824 var setTimer = require('../env').setTimer;
20825 var format = require('../format');
20827 return function unhandledRejection(Promise) {
20829 var logError = noop;
20830 var logInfo = noop;
20833 if(typeof console !== 'undefined') {
20834 // Alias console to prevent things like uglify's drop_console option from
20835 // removing console.log/error. Unhandled rejections fall into the same
20836 // category as uncaught exceptions, and build tools shouldn't silence them.
20837 localConsole = console;
20838 logError = typeof localConsole.error !== 'undefined'
20839 ? function (e) { localConsole.error(e); }
20840 : function (e) { localConsole.log(e); };
20842 logInfo = typeof localConsole.info !== 'undefined'
20843 ? function (e) { localConsole.info(e); }
20844 : function (e) { localConsole.log(e); };
20847 Promise.onPotentiallyUnhandledRejection = function(rejection) {
20848 enqueue(report, rejection);
20851 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
20852 enqueue(unreport, rejection);
20855 Promise.onFatalRejection = function(rejection) {
20856 enqueue(throwit, rejection.value);
20861 var running = null;
20863 function report(r) {
20866 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
20870 function unreport(r) {
20871 var i = reported.indexOf(r);
20873 reported.splice(i, 1);
20874 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
20878 function enqueue(f, x) {
20880 if(running === null) {
20881 running = setTimer(flush, 0);
20887 while(tasks.length > 0) {
20888 tasks.shift()(tasks.shift());
20895 function throwit(e) {
20902 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20904 },{"../env":274,"../format":275}],273:[function(require,module,exports){
20905 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20906 /** @author Brian Cavalier */
20907 /** @author John Hann */
20909 (function(define) { 'use strict';
20910 define(function() {
20912 return function addWith(Promise) {
20914 * Returns a promise whose handlers will be called with `this` set to
20915 * the supplied receiver. Subsequent promises derived from the
20916 * returned promise will also have their handlers called with receiver
20917 * as `this`. Calling `with` with undefined or no arguments will return
20918 * a promise whose handlers will again be called in the usual Promises/A+
20919 * way (no `this`) thus safely undoing any previous `with` in the
20922 * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
20923 * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
20925 * @param {object} receiver `this` value for all handlers attached to
20926 * the returned promise.
20927 * @returns {Promise}
20929 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
20930 var p = this._beget();
20931 var child = p._handler;
20932 child.receiver = receiver;
20933 this._handler.chain(child, receiver);
20941 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20944 },{}],274:[function(require,module,exports){
20945 (function (process){
20946 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20947 /** @author Brian Cavalier */
20948 /** @author John Hann */
20950 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
20951 (function(define) { 'use strict';
20952 define(function(require) {
20953 /*jshint maxcomplexity:6*/
20955 // Sniff "best" async scheduling option
20956 // Prefer process.nextTick or MutationObserver, then check for
20957 // setTimeout, and finally vertx, since its the only env that doesn't
20961 var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
20964 var setTimer = function(f, ms) { return setTimeout(f, ms); };
20965 var clearTimer = function(t) { return clearTimeout(t); };
20966 var asap = function (f) { return capturedSetTimeout(f, 0); };
20968 // Detect specific env
20969 if (isNode()) { // Node
20970 asap = function (f) { return process.nextTick(f); };
20972 } else if (MutationObs = hasMutationObserver()) { // Modern browser
20973 asap = initMutationObserver(MutationObs);
20975 } else if (!capturedSetTimeout) { // vert.x
20976 var vertxRequire = require;
20977 var vertx = vertxRequire('vertx');
20978 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
20979 clearTimer = vertx.cancelTimer;
20980 asap = vertx.runOnLoop || vertx.runOnContext;
20984 setTimer: setTimer,
20985 clearTimer: clearTimer,
20989 function isNode () {
20990 return typeof process !== 'undefined' &&
20991 Object.prototype.toString.call(process) === '[object process]';
20994 function hasMutationObserver () {
20995 return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
20996 (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
20999 function initMutationObserver(MutationObserver) {
21001 var node = document.createTextNode('');
21002 var o = new MutationObserver(run);
21003 o.observe(node, { characterData: true });
21007 scheduled = void 0;
21012 return function (f) {
21014 node.data = (i ^= 1);
21018 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21020 }).call(this,require('_process'))
21022 },{"_process":6}],275:[function(require,module,exports){
21023 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21024 /** @author Brian Cavalier */
21025 /** @author John Hann */
21027 (function(define) { 'use strict';
21028 define(function() {
21031 formatError: formatError,
21032 formatObject: formatObject,
21033 tryStringify: tryStringify
21037 * Format an error into a string. If e is an Error and has a stack property,
21038 * it's returned. Otherwise, e is formatted using formatObject, with a
21039 * warning added about e not being a proper Error.
21041 * @returns {String} formatted string, suitable for output to developers
21043 function formatError(e) {
21044 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
21045 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
21049 * Format an object, detecting "plain" objects and running them through
21050 * JSON.stringify if possible.
21051 * @param {Object} o
21052 * @returns {string}
21054 function formatObject(o) {
21056 if(s === '[object Object]' && typeof JSON !== 'undefined') {
21057 s = tryStringify(o, s);
21063 * Try to return the result of JSON.stringify(x). If that fails, return
21066 * @param {*} defaultValue
21067 * @returns {String|*} JSON.stringify(x) or defaultValue
21069 function tryStringify(x, defaultValue) {
21071 return JSON.stringify(x);
21073 return defaultValue;
21078 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21080 },{}],276:[function(require,module,exports){
21081 (function (process){
21082 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21083 /** @author Brian Cavalier */
21084 /** @author John Hann */
21086 (function(define) { 'use strict';
21087 define(function() {
21089 return function makePromise(environment) {
21091 var tasks = environment.scheduler;
21092 var emitRejection = initEmitRejection();
21094 var objectCreate = Object.create ||
21096 function Child() {}
21097 Child.prototype = proto;
21098 return new Child();
21102 * Create a promise whose fate is determined by resolver
21104 * @returns {Promise} promise
21107 function Promise(resolver, handler) {
21108 this._handler = resolver === Handler ? handler : init(resolver);
21112 * Run the supplied resolver
21114 * @returns {Pending}
21116 function init(resolver) {
21117 var handler = new Pending();
21120 resolver(promiseResolve, promiseReject, promiseNotify);
21128 * Transition from pre-resolution state to post-resolution state, notifying
21129 * all listeners of the ultimate fulfillment or rejection
21130 * @param {*} x resolution value
21132 function promiseResolve (x) {
21133 handler.resolve(x);
21136 * Reject this promise with reason, which will be used verbatim
21137 * @param {Error|*} reason rejection reason, strongly suggested
21138 * to be an Error type
21140 function promiseReject (reason) {
21141 handler.reject(reason);
21146 * Issue a progress event, notifying all progress listeners
21147 * @param {*} x progress event payload to pass to all listeners
21149 function promiseNotify (x) {
21156 Promise.resolve = resolve;
21157 Promise.reject = reject;
21158 Promise.never = never;
21160 Promise._defer = defer;
21161 Promise._handler = getHandler;
21164 * Returns a trusted promise. If x is already a trusted promise, it is
21165 * returned, otherwise returns a new trusted Promise which follows x.
21167 * @return {Promise} promise
21169 function resolve(x) {
21170 return isPromise(x) ? x
21171 : new Promise(Handler, new Async(getHandler(x)));
21175 * Return a reject promise with x as its reason (x is used verbatim)
21177 * @returns {Promise} rejected promise
21179 function reject(x) {
21180 return new Promise(Handler, new Async(new Rejected(x)));
21184 * Return a promise that remains pending forever
21185 * @returns {Promise} forever-pending promise.
21188 return foreverPendingPromise; // Should be frozen
21192 * Creates an internal {promise, resolver} pair
21194 * @returns {Promise}
21197 return new Promise(Handler, new Pending());
21200 // Transformation and flow control
21203 * Transform this promise's fulfillment value, returning a new Promise
21204 * for the transformed result. If the promise cannot be fulfilled, onRejected
21205 * is called with the reason. onProgress *may* be called with updates toward
21206 * this promise's fulfillment.
21207 * @param {function=} onFulfilled fulfillment handler
21208 * @param {function=} onRejected rejection handler
21209 * @param {function=} onProgress @deprecated progress handler
21210 * @return {Promise} new promise
21212 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
21213 var parent = this._handler;
21214 var state = parent.join().state();
21216 if ((typeof onFulfilled !== 'function' && state > 0) ||
21217 (typeof onRejected !== 'function' && state < 0)) {
21218 // Short circuit: value will not change, simply share handler
21219 return new this.constructor(Handler, parent);
21222 var p = this._beget();
21223 var child = p._handler;
21225 parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
21231 * If this promise cannot be fulfilled due to an error, call onRejected to
21232 * handle the error. Shortcut for .then(undefined, onRejected)
21233 * @param {function?} onRejected
21234 * @return {Promise}
21236 Promise.prototype['catch'] = function(onRejected) {
21237 return this.then(void 0, onRejected);
21241 * Creates a new, pending promise of the same type as this promise
21243 * @returns {Promise}
21245 Promise.prototype._beget = function() {
21246 return begetFrom(this._handler, this.constructor);
21249 function begetFrom(parent, Promise) {
21250 var child = new Pending(parent.receiver, parent.join().context);
21251 return new Promise(Handler, child);
21254 // Array combinators
21257 Promise.race = race;
21258 Promise._traverse = traverse;
21261 * Return a promise that will fulfill when all promises in the
21262 * input array have fulfilled, or will reject when one of the
21263 * promises rejects.
21264 * @param {array} promises array of promises
21265 * @returns {Promise} promise for array of fulfillment values
21267 function all(promises) {
21268 return traverseWith(snd, null, promises);
21272 * Array<Promise<X>> -> Promise<Array<f(X)>>
21274 * @param {function} f function to apply to each promise's value
21275 * @param {Array} promises array of promises
21276 * @returns {Promise} promise for transformed values
21278 function traverse(f, promises) {
21279 return traverseWith(tryCatch2, f, promises);
21282 function traverseWith(tryMap, f, promises) {
21283 var handler = typeof f === 'function' ? mapAt : settleAt;
21285 var resolver = new Pending();
21286 var pending = promises.length >>> 0;
21287 var results = new Array(pending);
21289 for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
21292 if (x === void 0 && !(i in promises)) {
21297 traverseAt(promises, handler, i, x, resolver);
21300 if(pending === 0) {
21301 resolver.become(new Fulfilled(results));
21304 return new Promise(Handler, resolver);
21306 function mapAt(i, x, resolver) {
21307 if(!resolver.resolved) {
21308 traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
21312 function settleAt(i, x, resolver) {
21314 if(--pending === 0) {
21315 resolver.become(new Fulfilled(results));
21320 function traverseAt(promises, handler, i, x, resolver) {
21321 if (maybeThenable(x)) {
21322 var h = getHandlerMaybeThenable(x);
21326 h.fold(handler, i, void 0, resolver);
21327 } else if (s > 0) {
21328 handler(i, h.value, resolver);
21330 resolver.become(h);
21331 visitRemaining(promises, i+1, h);
21334 handler(i, x, resolver);
21338 Promise._visitRemaining = visitRemaining;
21339 function visitRemaining(promises, start, handler) {
21340 for(var i=start; i<promises.length; ++i) {
21341 markAsHandled(getHandler(promises[i]), handler);
21345 function markAsHandled(h, handler) {
21346 if(h === handler) {
21352 h.visit(h, void 0, h._unreport);
21359 * Fulfill-reject competitive race. Return a promise that will settle
21360 * to the same state as the earliest input promise to settle.
21362 * WARNING: The ES6 Promise spec requires that race()ing an empty array
21363 * must return a promise that is pending forever. This implementation
21364 * returns a singleton forever-pending promise, the same singleton that is
21365 * returned by Promise.never(), thus can be checked with ===
21367 * @param {array} promises array of promises to race
21368 * @returns {Promise} if input is non-empty, a promise that will settle
21369 * to the same outcome as the earliest input promise to settle. if empty
21370 * is empty, returns a promise that will never settle.
21372 function race(promises) {
21373 if(typeof promises !== 'object' || promises === null) {
21374 return reject(new TypeError('non-iterable passed to race()'));
21377 // Sigh, race([]) is untestable unless we return *something*
21378 // that is recognizable without calling .then() on it.
21379 return promises.length === 0 ? never()
21380 : promises.length === 1 ? resolve(promises[0])
21381 : runRace(promises);
21384 function runRace(promises) {
21385 var resolver = new Pending();
21387 for(i=0; i<promises.length; ++i) {
21389 if (x === void 0 && !(i in promises)) {
21394 if(h.state() !== 0) {
21395 resolver.become(h);
21396 visitRemaining(promises, i+1, h);
21399 h.visit(resolver, resolver.resolve, resolver.reject);
21402 return new Promise(Handler, resolver);
21405 // Promise internals
21406 // Below this, everything is @private
21409 * Get an appropriate handler for x, without checking for cycles
21411 * @returns {object} handler
21413 function getHandler(x) {
21415 return x._handler.join();
21417 return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
21421 * Get a handler for thenable x.
21422 * NOTE: You must only call this if maybeThenable(x) == true
21423 * @param {object|function|Promise} x
21424 * @returns {object} handler
21426 function getHandlerMaybeThenable(x) {
21427 return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
21431 * Get a handler for potentially untrusted thenable x
21433 * @returns {object} handler
21435 function getHandlerUntrusted(x) {
21437 var untrustedThen = x.then;
21438 return typeof untrustedThen === 'function'
21439 ? new Thenable(untrustedThen, x)
21440 : new Fulfilled(x);
21442 return new Rejected(e);
21447 * Handler for a promise that is pending forever
21450 function Handler() {}
21452 Handler.prototype.when
21453 = Handler.prototype.become
21454 = Handler.prototype.notify // deprecated
21455 = Handler.prototype.fail
21456 = Handler.prototype._unreport
21457 = Handler.prototype._report
21460 Handler.prototype._state = 0;
21462 Handler.prototype.state = function() {
21463 return this._state;
21467 * Recursively collapse handler chain to find the handler
21468 * nearest to the fully resolved value.
21469 * @returns {object} handler nearest the fully resolved value
21471 Handler.prototype.join = function() {
21473 while(h.handler !== void 0) {
21479 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
21482 receiver: receiver,
21483 fulfilled: fulfilled,
21484 rejected: rejected,
21489 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
21490 this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
21493 Handler.prototype.fold = function(f, z, c, to) {
21494 this.when(new Fold(f, z, c, to));
21498 * Handler that invokes fail() on any handler it becomes
21501 function FailIfRejected() {}
21503 inherit(Handler, FailIfRejected);
21505 FailIfRejected.prototype.become = function(h) {
21509 var failIfRejected = new FailIfRejected();
21512 * Handler that manages a queue of consumers waiting on a pending promise
21515 function Pending(receiver, inheritedContext) {
21516 Promise.createContext(this, inheritedContext);
21518 this.consumers = void 0;
21519 this.receiver = receiver;
21520 this.handler = void 0;
21521 this.resolved = false;
21524 inherit(Handler, Pending);
21526 Pending.prototype._state = 0;
21528 Pending.prototype.resolve = function(x) {
21529 this.become(getHandler(x));
21532 Pending.prototype.reject = function(x) {
21533 if(this.resolved) {
21537 this.become(new Rejected(x));
21540 Pending.prototype.join = function() {
21541 if (!this.resolved) {
21547 while (h.handler !== void 0) {
21550 return this.handler = cycle();
21557 Pending.prototype.run = function() {
21558 var q = this.consumers;
21559 var handler = this.handler;
21560 this.handler = this.handler.join();
21561 this.consumers = void 0;
21563 for (var i = 0; i < q.length; ++i) {
21564 handler.when(q[i]);
21568 Pending.prototype.become = function(handler) {
21569 if(this.resolved) {
21573 this.resolved = true;
21574 this.handler = handler;
21575 if(this.consumers !== void 0) {
21576 tasks.enqueue(this);
21579 if(this.context !== void 0) {
21580 handler._report(this.context);
21584 Pending.prototype.when = function(continuation) {
21585 if(this.resolved) {
21586 tasks.enqueue(new ContinuationTask(continuation, this.handler));
21588 if(this.consumers === void 0) {
21589 this.consumers = [continuation];
21591 this.consumers.push(continuation);
21599 Pending.prototype.notify = function(x) {
21600 if(!this.resolved) {
21601 tasks.enqueue(new ProgressTask(x, this));
21605 Pending.prototype.fail = function(context) {
21606 var c = typeof context === 'undefined' ? this.context : context;
21607 this.resolved && this.handler.join().fail(c);
21610 Pending.prototype._report = function(context) {
21611 this.resolved && this.handler.join()._report(context);
21614 Pending.prototype._unreport = function() {
21615 this.resolved && this.handler.join()._unreport();
21619 * Wrap another handler and force it into a future stack
21620 * @param {object} handler
21623 function Async(handler) {
21624 this.handler = handler;
21627 inherit(Handler, Async);
21629 Async.prototype.when = function(continuation) {
21630 tasks.enqueue(new ContinuationTask(continuation, this));
21633 Async.prototype._report = function(context) {
21634 this.join()._report(context);
21637 Async.prototype._unreport = function() {
21638 this.join()._unreport();
21642 * Handler that wraps an untrusted thenable and assimilates it in a future stack
21643 * @param {function} then
21644 * @param {{then: function}} thenable
21647 function Thenable(then, thenable) {
21648 Pending.call(this);
21649 tasks.enqueue(new AssimilateTask(then, thenable, this));
21652 inherit(Pending, Thenable);
21655 * Handler for a fulfilled promise
21656 * @param {*} x fulfillment value
21659 function Fulfilled(x) {
21660 Promise.createContext(this);
21664 inherit(Handler, Fulfilled);
21666 Fulfilled.prototype._state = 1;
21668 Fulfilled.prototype.fold = function(f, z, c, to) {
21669 runContinuation3(f, z, this, c, to);
21672 Fulfilled.prototype.when = function(cont) {
21673 runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
21679 * Handler for a rejected promise
21680 * @param {*} x rejection reason
21683 function Rejected(x) {
21684 Promise.createContext(this);
21686 this.id = ++errorId;
21688 this.handled = false;
21689 this.reported = false;
21694 inherit(Handler, Rejected);
21696 Rejected.prototype._state = -1;
21698 Rejected.prototype.fold = function(f, z, c, to) {
21702 Rejected.prototype.when = function(cont) {
21703 if(typeof cont.rejected === 'function') {
21706 runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
21709 Rejected.prototype._report = function(context) {
21710 tasks.afterQueue(new ReportTask(this, context));
21713 Rejected.prototype._unreport = function() {
21717 this.handled = true;
21718 tasks.afterQueue(new UnreportTask(this));
21721 Rejected.prototype.fail = function(context) {
21722 this.reported = true;
21723 emitRejection('unhandledRejection', this);
21724 Promise.onFatalRejection(this, context === void 0 ? this.context : context);
21727 function ReportTask(rejection, context) {
21728 this.rejection = rejection;
21729 this.context = context;
21732 ReportTask.prototype.run = function() {
21733 if(!this.rejection.handled && !this.rejection.reported) {
21734 this.rejection.reported = true;
21735 emitRejection('unhandledRejection', this.rejection) ||
21736 Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
21740 function UnreportTask(rejection) {
21741 this.rejection = rejection;
21744 UnreportTask.prototype.run = function() {
21745 if(this.rejection.reported) {
21746 emitRejection('rejectionHandled', this.rejection) ||
21747 Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
21751 // Unhandled rejection hooks
21752 // By default, everything is a noop
21754 Promise.createContext
21755 = Promise.enterContext
21756 = Promise.exitContext
21757 = Promise.onPotentiallyUnhandledRejection
21758 = Promise.onPotentiallyUnhandledRejectionHandled
21759 = Promise.onFatalRejection
21762 // Errors and singletons
21764 var foreverPendingHandler = new Handler();
21765 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
21768 return new Rejected(new TypeError('Promise cycle'));
21774 * Run a single consumer
21777 function ContinuationTask(continuation, handler) {
21778 this.continuation = continuation;
21779 this.handler = handler;
21782 ContinuationTask.prototype.run = function() {
21783 this.handler.join().when(this.continuation);
21787 * Run a queue of progress handlers
21790 function ProgressTask(value, handler) {
21791 this.handler = handler;
21792 this.value = value;
21795 ProgressTask.prototype.run = function() {
21796 var q = this.handler.consumers;
21801 for (var c, i = 0; i < q.length; ++i) {
21803 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
21808 * Assimilate a thenable, sending it's value to resolver
21809 * @param {function} then
21810 * @param {object|function} thenable
21811 * @param {object} resolver
21814 function AssimilateTask(then, thenable, resolver) {
21816 this.thenable = thenable;
21817 this.resolver = resolver;
21820 AssimilateTask.prototype.run = function() {
21821 var h = this.resolver;
21822 tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
21824 function _resolve(x) { h.resolve(x); }
21825 function _reject(x) { h.reject(x); }
21826 function _notify(x) { h.notify(x); }
21829 function tryAssimilate(then, thenable, resolve, reject, notify) {
21831 then.call(thenable, resolve, reject, notify);
21838 * Fold a handler value with z
21841 function Fold(f, z, c, to) {
21842 this.f = f; this.z = z; this.c = c; this.to = to;
21843 this.resolver = failIfRejected;
21844 this.receiver = this;
21847 Fold.prototype.fulfilled = function(x) {
21848 this.f.call(this.c, this.z, x, this.to);
21851 Fold.prototype.rejected = function(x) {
21855 Fold.prototype.progress = function(x) {
21863 * @returns {boolean} true iff x is a trusted Promise
21865 function isPromise(x) {
21866 return x instanceof Promise;
21870 * Test just enough to rule out primitives, in order to take faster
21871 * paths in some code
21873 * @returns {boolean} false iff x is guaranteed *not* to be a thenable
21875 function maybeThenable(x) {
21876 return (typeof x === 'object' || typeof x === 'function') && x !== null;
21879 function runContinuation1(f, h, receiver, next) {
21880 if(typeof f !== 'function') {
21881 return next.become(h);
21884 Promise.enterContext(h);
21885 tryCatchReject(f, h.value, receiver, next);
21886 Promise.exitContext();
21889 function runContinuation3(f, x, h, receiver, next) {
21890 if(typeof f !== 'function') {
21891 return next.become(h);
21894 Promise.enterContext(h);
21895 tryCatchReject3(f, x, h.value, receiver, next);
21896 Promise.exitContext();
21902 function runNotify(f, x, h, receiver, next) {
21903 if(typeof f !== 'function') {
21904 return next.notify(x);
21907 Promise.enterContext(h);
21908 tryCatchReturn(f, x, receiver, next);
21909 Promise.exitContext();
21912 function tryCatch2(f, a, b) {
21921 * Return f.call(thisArg, x), or if it throws return a rejected promise for
21922 * the thrown exception
21924 function tryCatchReject(f, x, thisArg, next) {
21926 next.become(getHandler(f.call(thisArg, x)));
21928 next.become(new Rejected(e));
21933 * Same as above, but includes the extra argument parameter.
21935 function tryCatchReject3(f, x, y, thisArg, next) {
21937 f.call(thisArg, x, y, next);
21939 next.become(new Rejected(e));
21945 * Return f.call(thisArg, x), or if it throws, *return* the exception
21947 function tryCatchReturn(f, x, thisArg, next) {
21949 next.notify(f.call(thisArg, x));
21955 function inherit(Parent, Child) {
21956 Child.prototype = objectCreate(Parent.prototype);
21957 Child.prototype.constructor = Child;
21960 function snd(x, y) {
21966 function hasCustomEvent() {
21967 if(typeof CustomEvent === 'function') {
21969 var ev = new CustomEvent('unhandledRejection');
21970 return ev instanceof CustomEvent;
21971 } catch (ignoredException) {}
21976 function hasInternetExplorerCustomEvent() {
21977 if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
21979 // Try to create one event to make sure it's supported
21980 var ev = document.createEvent('CustomEvent');
21981 ev.initCustomEvent('eventType', false, true, {});
21983 } catch (ignoredException) {}
21988 function initEmitRejection() {
21989 /*global process, self, CustomEvent*/
21990 if(typeof process !== 'undefined' && process !== null
21991 && typeof process.emit === 'function') {
21992 // Returning falsy here means to call the default
21993 // onPotentiallyUnhandledRejection API. This is safe even in
21994 // browserify since process.emit always returns falsy in browserify:
21995 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
21996 return function(type, rejection) {
21997 return type === 'unhandledRejection'
21998 ? process.emit(type, rejection.value, rejection)
21999 : process.emit(type, rejection);
22001 } else if(typeof self !== 'undefined' && hasCustomEvent()) {
22002 return (function (self, CustomEvent) {
22003 return function (type, rejection) {
22004 var ev = new CustomEvent(type, {
22006 reason: rejection.value,
22013 return !self.dispatchEvent(ev);
22015 }(self, CustomEvent));
22016 } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
22017 return (function(self, document) {
22018 return function(type, rejection) {
22019 var ev = document.createEvent('CustomEvent');
22020 ev.initCustomEvent(type, false, true, {
22021 reason: rejection.value,
22025 return !self.dispatchEvent(ev);
22027 }(self, document));
22036 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
22038 }).call(this,require('_process'))
22040 },{"_process":6}],277:[function(require,module,exports){
22041 /** @license MIT License (c) copyright 2010-2014 original author or authors */
22042 /** @author Brian Cavalier */
22043 /** @author John Hann */
22045 (function(define) { 'use strict';
22046 define(function() {
22049 pending: toPendingState,
22050 fulfilled: toFulfilledState,
22051 rejected: toRejectedState,
22055 function toPendingState() {
22056 return { state: 'pending' };
22059 function toRejectedState(e) {
22060 return { state: 'rejected', reason: e };
22063 function toFulfilledState(x) {
22064 return { state: 'fulfilled', value: x };
22067 function inspect(handler) {
22068 var state = handler.state();
22069 return state === 0 ? toPendingState()
22070 : state > 0 ? toFulfilledState(handler.value)
22071 : toRejectedState(handler.value);
22075 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
22077 },{}],278:[function(require,module,exports){
22078 /** @license MIT License (c) copyright 2010-2014 original author or authors */
22081 * Promises/A+ and when() implementation
22082 * when is part of the cujoJS family of libraries (http://cujojs.com/)
22083 * @author Brian Cavalier
22084 * @author John Hann
22086 (function(define) { 'use strict';
22087 define(function (require) {
22089 var timed = require('./lib/decorators/timed');
22090 var array = require('./lib/decorators/array');
22091 var flow = require('./lib/decorators/flow');
22092 var fold = require('./lib/decorators/fold');
22093 var inspect = require('./lib/decorators/inspect');
22094 var generate = require('./lib/decorators/iterate');
22095 var progress = require('./lib/decorators/progress');
22096 var withThis = require('./lib/decorators/with');
22097 var unhandledRejection = require('./lib/decorators/unhandledRejection');
22098 var TimeoutError = require('./lib/TimeoutError');
22100 var Promise = [array, flow, fold, generate, progress,
22101 inspect, withThis, timed, unhandledRejection]
22102 .reduce(function(Promise, feature) {
22103 return feature(Promise);
22104 }, require('./lib/Promise'));
22106 var apply = require('./lib/apply')(Promise);
22110 when.promise = promise; // Create a pending promise
22111 when.resolve = Promise.resolve; // Create a resolved promise
22112 when.reject = Promise.reject; // Create a rejected promise
22114 when.lift = lift; // lift a function to return promises
22115 when['try'] = attempt; // call a function and return a promise
22116 when.attempt = attempt; // alias for when.try
22118 when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
22119 when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
22121 when.join = join; // Join 2 or more promises
22123 when.all = all; // Resolve a list of promises
22124 when.settle = settle; // Settle a list of promises
22126 when.any = lift(Promise.any); // One-winner race
22127 when.some = lift(Promise.some); // Multi-winner race
22128 when.race = lift(Promise.race); // First-to-settle race
22130 when.map = map; // Array.map() for promises
22131 when.filter = filter; // Array.filter() for promises
22132 when.reduce = lift(Promise.reduce); // Array.reduce() for promises
22133 when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
22135 when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
22137 when.Promise = Promise; // Promise constructor
22138 when.defer = defer; // Create a {promise, resolve, reject} tuple
22142 when.TimeoutError = TimeoutError;
22145 * Get a trusted promise for x, or by transforming x with onFulfilled
22148 * @param {function?} onFulfilled callback to be called when x is
22149 * successfully fulfilled. If promiseOrValue is an immediate value, callback
22150 * will be invoked immediately.
22151 * @param {function?} onRejected callback to be called when x is
22153 * @param {function?} onProgress callback to be called when progress updates
22154 * are issued for x. @deprecated
22155 * @returns {Promise} a new promise that will fulfill with the return
22156 * value of callback or errback or the completion value of promiseOrValue if
22157 * callback and/or errback is not supplied.
22159 function when(x, onFulfilled, onRejected, onProgress) {
22160 var p = Promise.resolve(x);
22161 if (arguments.length < 2) {
22165 return p.then(onFulfilled, onRejected, onProgress);
22169 * Creates a new promise whose fate is determined by resolver.
22170 * @param {function} resolver function(resolve, reject, notify)
22171 * @returns {Promise} promise whose fate is determine by resolver
22173 function promise(resolver) {
22174 return new Promise(resolver);
22178 * Lift the supplied function, creating a version of f that returns
22179 * promises, and accepts promises as arguments.
22180 * @param {function} f
22181 * @returns {Function} version of f that returns promises
22184 return function() {
22185 for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
22186 a[i] = arguments[i];
22188 return apply(f, this, a);
22193 * Call f in a future turn, with the supplied args, and return a promise
22195 * @param {function} f
22196 * @returns {Promise}
22198 function attempt(f /*, args... */) {
22199 /*jshint validthis:true */
22200 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
22201 a[i] = arguments[i+1];
22203 return apply(f, this, a);
22207 * Creates a {promise, resolver} pair, either or both of which
22208 * may be given out safely to consumers.
22209 * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
22212 return new Deferred();
22215 function Deferred() {
22216 var p = Promise._defer();
22218 function resolve(x) { p._handler.resolve(x); }
22219 function reject(x) { p._handler.reject(x); }
22220 function notify(x) { p._handler.notify(x); }
22223 this.resolve = resolve;
22224 this.reject = reject;
22225 this.notify = notify;
22226 this.resolver = { resolve: resolve, reject: reject, notify: notify };
22230 * Determines if x is promise-like, i.e. a thenable object
22231 * NOTE: Will return true for *any thenable object*, and isn't truly
22232 * safe, since it may attempt to access the `then` property of x (i.e.
22233 * clever/malicious getters may do weird things)
22234 * @param {*} x anything
22235 * @returns {boolean} true if x is promise-like
22237 function isPromiseLike(x) {
22238 return x && typeof x.then === 'function';
22242 * Return a promise that will resolve only once all the supplied arguments
22243 * have resolved. The resolution value of the returned promise will be an array
22244 * containing the resolution values of each of the arguments.
22245 * @param {...*} arguments may be a mix of promises and values
22246 * @returns {Promise}
22248 function join(/* ...promises */) {
22249 return Promise.all(arguments);
22253 * Return a promise that will fulfill once all input promises have
22254 * fulfilled, or reject when any one input promise rejects.
22255 * @param {array|Promise} promises array (or promise for an array) of promises
22256 * @returns {Promise}
22258 function all(promises) {
22259 return when(promises, Promise.all);
22263 * Return a promise that will always fulfill with an array containing
22264 * the outcome states of all input promises. The returned promise
22265 * will only reject if `promises` itself is a rejected promise.
22266 * @param {array|Promise} promises array (or promise for an array) of promises
22267 * @returns {Promise} promise for array of settled state descriptors
22269 function settle(promises) {
22270 return when(promises, Promise.settle);
22274 * Promise-aware array map function, similar to `Array.prototype.map()`,
22275 * but input array may contain promises or values.
22276 * @param {Array|Promise} promises array of anything, may contain promises and values
22277 * @param {function(x:*, index:Number):*} mapFunc map function which may
22278 * return a promise or value
22279 * @returns {Promise} promise that will fulfill with an array of mapped values
22280 * or reject if any input promise rejects.
22282 function map(promises, mapFunc) {
22283 return when(promises, function(promises) {
22284 return Promise.map(promises, mapFunc);
22289 * Filter the provided array of promises using the provided predicate. Input may
22290 * contain promises and values
22291 * @param {Array|Promise} promises array of promises and values
22292 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
22293 * Must return truthy (or promise for truthy) for items to retain.
22294 * @returns {Promise} promise that will fulfill with an array containing all items
22295 * for which predicate returned truthy.
22297 function filter(promises, predicate) {
22298 return when(promises, function(promises) {
22299 return Promise.filter(promises, predicate);
22305 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
22307 },{"./lib/Promise":261,"./lib/TimeoutError":263,"./lib/apply":264,"./lib/decorators/array":265,"./lib/decorators/flow":266,"./lib/decorators/fold":267,"./lib/decorators/inspect":268,"./lib/decorators/iterate":269,"./lib/decorators/progress":270,"./lib/decorators/timed":271,"./lib/decorators/unhandledRejection":272,"./lib/decorators/with":273}],279:[function(require,module,exports){
22308 var nativeIsArray = Array.isArray
22309 var toString = Object.prototype.toString
22311 module.exports = nativeIsArray || isArray
22313 function isArray(obj) {
22314 return toString.call(obj) === "[object Array]"
22317 },{}],280:[function(require,module,exports){
22319 Object.defineProperty(exports, "__esModule", { value: true });
22320 var APIv3_1 = require("./api/APIv3");
22321 exports.APIv3 = APIv3_1.APIv3;
22322 var ModelCreator_1 = require("./api/ModelCreator");
22323 exports.ModelCreator = ModelCreator_1.ModelCreator;
22325 },{"./api/APIv3":293,"./api/ModelCreator":294}],281:[function(require,module,exports){
22327 function __export(m) {
22328 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22330 Object.defineProperty(exports, "__esModule", { value: true });
22331 var Component_1 = require("./component/Component");
22332 exports.Component = Component_1.Component;
22333 var ComponentService_1 = require("./component/ComponentService");
22334 exports.ComponentService = ComponentService_1.ComponentService;
22335 var HandlerBase_1 = require("./component/utils/HandlerBase");
22336 exports.HandlerBase = HandlerBase_1.HandlerBase;
22337 var AttributionComponent_1 = require("./component/AttributionComponent");
22338 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
22339 var BackgroundComponent_1 = require("./component/BackgroundComponent");
22340 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
22341 var BearingComponent_1 = require("./component/BearingComponent");
22342 exports.BearingComponent = BearingComponent_1.BearingComponent;
22343 var CacheComponent_1 = require("./component/CacheComponent");
22344 exports.CacheComponent = CacheComponent_1.CacheComponent;
22345 var CoverComponent_1 = require("./component/CoverComponent");
22346 exports.CoverComponent = CoverComponent_1.CoverComponent;
22347 var DebugComponent_1 = require("./component/DebugComponent");
22348 exports.DebugComponent = DebugComponent_1.DebugComponent;
22349 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
22350 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
22351 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
22352 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
22353 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
22354 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
22355 var ImageComponent_1 = require("./component/ImageComponent");
22356 exports.ImageComponent = ImageComponent_1.ImageComponent;
22357 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
22358 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
22359 var KeyPlayHandler_1 = require("./component/keyboard/KeyPlayHandler");
22360 exports.KeyPlayHandler = KeyPlayHandler_1.KeyPlayHandler;
22361 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
22362 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
22363 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
22364 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
22365 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
22366 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
22367 var LoadingComponent_1 = require("./component/LoadingComponent");
22368 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
22369 var Marker_1 = require("./component/marker/marker/Marker");
22370 exports.Marker = Marker_1.Marker;
22371 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
22372 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
22373 var MarkerScene_1 = require("./component/marker/MarkerScene");
22374 exports.MarkerScene = MarkerScene_1.MarkerScene;
22375 var MarkerSet_1 = require("./component/marker/MarkerSet");
22376 exports.MarkerSet = MarkerSet_1.MarkerSet;
22377 var MouseComponent_1 = require("./component/mouse/MouseComponent");
22378 exports.MouseComponent = MouseComponent_1.MouseComponent;
22379 var BounceHandler_1 = require("./component/mouse/BounceHandler");
22380 exports.BounceHandler = BounceHandler_1.BounceHandler;
22381 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
22382 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
22383 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
22384 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
22385 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
22386 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
22387 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
22388 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
22389 var Popup_1 = require("./component/popup/popup/Popup");
22390 exports.Popup = Popup_1.Popup;
22391 var PopupComponent_1 = require("./component/popup/PopupComponent");
22392 exports.PopupComponent = PopupComponent_1.PopupComponent;
22393 var NavigationComponent_1 = require("./component/NavigationComponent");
22394 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
22395 var RouteComponent_1 = require("./component/RouteComponent");
22396 exports.RouteComponent = RouteComponent_1.RouteComponent;
22397 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
22398 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
22399 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
22400 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
22401 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
22402 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
22403 var ControlMode_1 = require("./component/sequence/ControlMode");
22404 exports.ControlMode = ControlMode_1.ControlMode;
22405 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
22406 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
22407 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
22408 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
22409 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
22410 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
22411 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
22412 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
22413 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
22414 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
22415 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
22416 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
22417 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
22418 exports.CircleMarker = CircleMarker_1.CircleMarker;
22419 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
22420 exports.SliderComponent = SliderComponent_1.SliderComponent;
22421 var StatsComponent_1 = require("./component/StatsComponent");
22422 exports.StatsComponent = StatsComponent_1.StatsComponent;
22423 var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase");
22424 exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase;
22425 var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase");
22426 exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase;
22427 var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler");
22428 exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler;
22429 var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler");
22430 exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler;
22431 var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler");
22432 exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler;
22433 var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler");
22434 exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler;
22435 var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler");
22436 exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler;
22437 var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler");
22438 exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler;
22439 var Tag_1 = require("./component/tag/tag/Tag");
22440 exports.Tag = Tag_1.Tag;
22441 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
22442 exports.OutlineTag = OutlineTag_1.OutlineTag;
22443 var RenderTag_1 = require("./component/tag/tag/RenderTag");
22444 exports.RenderTag = RenderTag_1.RenderTag;
22445 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
22446 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
22447 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
22448 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
22449 var SpotTag_1 = require("./component/tag/tag/SpotTag");
22450 exports.SpotTag = SpotTag_1.SpotTag;
22451 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
22452 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
22453 var TagComponent_1 = require("./component/tag/TagComponent");
22454 exports.TagComponent = TagComponent_1.TagComponent;
22455 var TagCreator_1 = require("./component/tag/TagCreator");
22456 exports.TagCreator = TagCreator_1.TagCreator;
22457 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
22458 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
22459 var TagMode_1 = require("./component/tag/TagMode");
22460 exports.TagMode = TagMode_1.TagMode;
22461 var TagOperation_1 = require("./component/tag/TagOperation");
22462 exports.TagOperation = TagOperation_1.TagOperation;
22463 var TagScene_1 = require("./component/tag/TagScene");
22464 exports.TagScene = TagScene_1.TagScene;
22465 var TagSet_1 = require("./component/tag/TagSet");
22466 exports.TagSet = TagSet_1.TagSet;
22467 var Geometry_1 = require("./component/tag/geometry/Geometry");
22468 exports.Geometry = Geometry_1.Geometry;
22469 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
22470 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
22471 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
22472 exports.RectGeometry = RectGeometry_1.RectGeometry;
22473 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
22474 exports.PointGeometry = PointGeometry_1.PointGeometry;
22475 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
22476 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
22477 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
22478 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
22479 __export(require("./component/interfaces/interfaces"));
22481 },{"./component/AttributionComponent":295,"./component/BackgroundComponent":296,"./component/BearingComponent":297,"./component/CacheComponent":298,"./component/Component":299,"./component/ComponentService":300,"./component/CoverComponent":301,"./component/DebugComponent":302,"./component/ImageComponent":303,"./component/LoadingComponent":304,"./component/NavigationComponent":305,"./component/RouteComponent":306,"./component/StatsComponent":307,"./component/direction/DirectionComponent":308,"./component/direction/DirectionDOMCalculator":309,"./component/direction/DirectionDOMRenderer":310,"./component/imageplane/ImagePlaneComponent":311,"./component/imageplane/ImagePlaneFactory":312,"./component/imageplane/ImagePlaneGLRenderer":313,"./component/imageplane/ImagePlaneScene":314,"./component/imageplane/ImagePlaneShaders":315,"./component/imageplane/SliderComponent":316,"./component/interfaces/interfaces":318,"./component/keyboard/KeyPlayHandler":319,"./component/keyboard/KeySequenceNavigationHandler":320,"./component/keyboard/KeySpatialNavigationHandler":321,"./component/keyboard/KeyZoomHandler":322,"./component/keyboard/KeyboardComponent":323,"./component/marker/MarkerComponent":325,"./component/marker/MarkerScene":326,"./component/marker/MarkerSet":327,"./component/marker/marker/CircleMarker":328,"./component/marker/marker/Marker":329,"./component/marker/marker/SimpleMarker":330,"./component/mouse/BounceHandler":331,"./component/mouse/DoubleClickZoomHandler":332,"./component/mouse/DragPanHandler":333,"./component/mouse/MouseComponent":334,"./component/mouse/ScrollZoomHandler":335,"./component/mouse/TouchZoomHandler":336,"./component/popup/PopupComponent":338,"./component/popup/popup/Popup":339,"./component/sequence/ControlMode":340,"./component/sequence/SequenceComponent":341,"./component/sequence/SequenceDOMInteraction":342,"./component/sequence/SequenceDOMRenderer":343,"./component/tag/TagComponent":345,"./component/tag/TagCreator":346,"./component/tag/TagDOMRenderer":347,"./component/tag/TagMode":348,"./component/tag/TagOperation":349,"./component/tag/TagScene":350,"./component/tag/TagSet":351,"./component/tag/error/GeometryTagError":352,"./component/tag/geometry/Geometry":353,"./component/tag/geometry/PointGeometry":354,"./component/tag/geometry/PolygonGeometry":355,"./component/tag/geometry/RectGeometry":356,"./component/tag/geometry/VertexGeometry":357,"./component/tag/handlers/CreateHandlerBase":358,"./component/tag/handlers/CreatePointHandler":359,"./component/tag/handlers/CreatePolygonHandler":360,"./component/tag/handlers/CreateRectDragHandler":361,"./component/tag/handlers/CreateRectHandler":362,"./component/tag/handlers/CreateVertexHandler":363,"./component/tag/handlers/EditVertexHandler":364,"./component/tag/handlers/TagHandlerBase":365,"./component/tag/tag/OutlineCreateTag":366,"./component/tag/tag/OutlineRenderTag":367,"./component/tag/tag/OutlineTag":368,"./component/tag/tag/RenderTag":369,"./component/tag/tag/SpotRenderTag":370,"./component/tag/tag/SpotTag":371,"./component/tag/tag/Tag":372,"./component/utils/HandlerBase":373}],282:[function(require,module,exports){
22483 Object.defineProperty(exports, "__esModule", { value: true });
22484 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
22485 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
22486 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
22487 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
22488 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
22489 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
22490 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
22491 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
22492 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
22493 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
22495 },{"./graph/edge/EdgeCalculator":392,"./graph/edge/EdgeCalculatorCoefficients":393,"./graph/edge/EdgeCalculatorDirections":394,"./graph/edge/EdgeCalculatorSettings":395,"./graph/edge/EdgeDirection":396}],283:[function(require,module,exports){
22497 Object.defineProperty(exports, "__esModule", { value: true });
22498 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
22499 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
22500 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
22501 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
22502 var MapillaryError_1 = require("./error/MapillaryError");
22503 exports.MapillaryError = MapillaryError_1.MapillaryError;
22505 },{"./error/ArgumentMapillaryError":374,"./error/GraphMapillaryError":375,"./error/MapillaryError":376}],284:[function(require,module,exports){
22507 Object.defineProperty(exports, "__esModule", { value: true });
22508 var Camera_1 = require("./geo/Camera");
22509 exports.Camera = Camera_1.Camera;
22510 var GeoCoords_1 = require("./geo/GeoCoords");
22511 exports.GeoCoords = GeoCoords_1.GeoCoords;
22512 var ViewportCoords_1 = require("./geo/ViewportCoords");
22513 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
22514 var Spatial_1 = require("./geo/Spatial");
22515 exports.Spatial = Spatial_1.Spatial;
22516 var Transform_1 = require("./geo/Transform");
22517 exports.Transform = Transform_1.Transform;
22519 },{"./geo/Camera":377,"./geo/GeoCoords":378,"./geo/Spatial":379,"./geo/Transform":380,"./geo/ViewportCoords":381}],285:[function(require,module,exports){
22521 Object.defineProperty(exports, "__esModule", { value: true });
22522 var FilterCreator_1 = require("./graph/FilterCreator");
22523 exports.FilterCreator = FilterCreator_1.FilterCreator;
22524 var Graph_1 = require("./graph/Graph");
22525 exports.Graph = Graph_1.Graph;
22526 var GraphCalculator_1 = require("./graph/GraphCalculator");
22527 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
22528 var GraphMode_1 = require("./graph/GraphMode");
22529 exports.GraphMode = GraphMode_1.GraphMode;
22530 var GraphService_1 = require("./graph/GraphService");
22531 exports.GraphService = GraphService_1.GraphService;
22532 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
22533 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
22534 var MeshReader_1 = require("./graph/MeshReader");
22535 exports.MeshReader = MeshReader_1.MeshReader;
22536 var Node_1 = require("./graph/Node");
22537 exports.Node = Node_1.Node;
22538 var NodeCache_1 = require("./graph/NodeCache");
22539 exports.NodeCache = NodeCache_1.NodeCache;
22540 var Sequence_1 = require("./graph/Sequence");
22541 exports.Sequence = Sequence_1.Sequence;
22543 },{"./graph/FilterCreator":382,"./graph/Graph":383,"./graph/GraphCalculator":384,"./graph/GraphMode":385,"./graph/GraphService":386,"./graph/ImageLoadingService":387,"./graph/MeshReader":388,"./graph/Node":389,"./graph/NodeCache":390,"./graph/Sequence":391}],286:[function(require,module,exports){
22546 * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
22549 function __export(m) {
22550 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22552 Object.defineProperty(exports, "__esModule", { value: true });
22553 __export(require("./Support"));
22554 var Edge_1 = require("./Edge");
22555 exports.EdgeDirection = Edge_1.EdgeDirection;
22556 var Render_1 = require("./Render");
22557 exports.RenderMode = Render_1.RenderMode;
22558 var Viewer_1 = require("./Viewer");
22559 exports.Alignment = Viewer_1.Alignment;
22560 exports.ImageSize = Viewer_1.ImageSize;
22561 exports.Viewer = Viewer_1.Viewer;
22562 var TagComponent = require("./component/tag/Tag");
22563 exports.TagComponent = TagComponent;
22564 var MarkerComponent = require("./component/marker/Marker");
22565 exports.MarkerComponent = MarkerComponent;
22566 var PopupComponent = require("./component/popup/Popup");
22567 exports.PopupComponent = PopupComponent;
22569 },{"./Edge":282,"./Render":287,"./Support":289,"./Viewer":292,"./component/marker/Marker":324,"./component/popup/Popup":337,"./component/tag/Tag":344}],287:[function(require,module,exports){
22571 Object.defineProperty(exports, "__esModule", { value: true });
22572 var DOMRenderer_1 = require("./render/DOMRenderer");
22573 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
22574 var GLRenderer_1 = require("./render/GLRenderer");
22575 exports.GLRenderer = GLRenderer_1.GLRenderer;
22576 var GLRenderStage_1 = require("./render/GLRenderStage");
22577 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
22578 var RenderCamera_1 = require("./render/RenderCamera");
22579 exports.RenderCamera = RenderCamera_1.RenderCamera;
22580 var RenderMode_1 = require("./render/RenderMode");
22581 exports.RenderMode = RenderMode_1.RenderMode;
22582 var RenderService_1 = require("./render/RenderService");
22583 exports.RenderService = RenderService_1.RenderService;
22585 },{"./render/DOMRenderer":397,"./render/GLRenderStage":398,"./render/GLRenderer":399,"./render/RenderCamera":400,"./render/RenderMode":401,"./render/RenderService":402}],288:[function(require,module,exports){
22587 Object.defineProperty(exports, "__esModule", { value: true });
22588 var State_1 = require("./state/State");
22589 exports.State = State_1.State;
22590 var StateBase_1 = require("./state/states/StateBase");
22591 exports.StateBase = StateBase_1.StateBase;
22592 var StateContext_1 = require("./state/StateContext");
22593 exports.StateContext = StateContext_1.StateContext;
22594 var StateService_1 = require("./state/StateService");
22595 exports.StateService = StateService_1.StateService;
22596 var TraversingState_1 = require("./state/states/TraversingState");
22597 exports.TraversingState = TraversingState_1.TraversingState;
22598 var WaitingState_1 = require("./state/states/WaitingState");
22599 exports.WaitingState = WaitingState_1.WaitingState;
22601 },{"./state/State":403,"./state/StateContext":404,"./state/StateService":405,"./state/states/StateBase":406,"./state/states/TraversingState":407,"./state/states/WaitingState":408}],289:[function(require,module,exports){
22603 Object.defineProperty(exports, "__esModule", { value: true });
22604 var support = require("./utils/Support");
22606 * Test whether the current browser supports the full
22607 * functionality of MapillaryJS.
22609 * @description The full functionality includes WebGL rendering.
22611 * @return {boolean}
22613 * @example `var supported = Mapillary.isSupported();`
22615 function isSupported() {
22616 return isFallbackSupported() &&
22617 support.isWebGLSupportedCached();
22619 exports.isSupported = isSupported;
22621 * Test whether the current browser supports the fallback
22622 * functionality of MapillaryJS.
22624 * @description The fallback functionality does not include WebGL
22625 * rendering, only 2D canvas rendering.
22627 * @return {boolean}
22629 * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
22631 function isFallbackSupported() {
22632 return support.isBrowser() &&
22633 support.isArraySupported() &&
22634 support.isFunctionSupported() &&
22635 support.isJSONSupported() &&
22636 support.isObjectSupported();
22638 exports.isFallbackSupported = isFallbackSupported;
22640 },{"./utils/Support":416}],290:[function(require,module,exports){
22642 Object.defineProperty(exports, "__esModule", { value: true });
22643 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
22644 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
22645 var ImageTileStore_1 = require("./tiles/ImageTileStore");
22646 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
22647 var TextureProvider_1 = require("./tiles/TextureProvider");
22648 exports.TextureProvider = TextureProvider_1.TextureProvider;
22649 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
22650 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
22652 },{"./tiles/ImageTileLoader":409,"./tiles/ImageTileStore":410,"./tiles/RegionOfInterestCalculator":411,"./tiles/TextureProvider":412}],291:[function(require,module,exports){
22654 function __export(m) {
22655 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22657 Object.defineProperty(exports, "__esModule", { value: true });
22658 var DOM_1 = require("./utils/DOM");
22659 exports.DOM = DOM_1.DOM;
22660 var EventEmitter_1 = require("./utils/EventEmitter");
22661 exports.EventEmitter = EventEmitter_1.EventEmitter;
22662 var Settings_1 = require("./utils/Settings");
22663 exports.Settings = Settings_1.Settings;
22664 __export(require("./utils/Support"));
22665 var Urls_1 = require("./utils/Urls");
22666 exports.Urls = Urls_1.Urls;
22668 },{"./utils/DOM":413,"./utils/EventEmitter":414,"./utils/Settings":415,"./utils/Support":416,"./utils/Urls":417}],292:[function(require,module,exports){
22670 Object.defineProperty(exports, "__esModule", { value: true });
22671 var Alignment_1 = require("./viewer/Alignment");
22672 exports.Alignment = Alignment_1.Alignment;
22673 var CacheService_1 = require("./viewer/CacheService");
22674 exports.CacheService = CacheService_1.CacheService;
22675 var ComponentController_1 = require("./viewer/ComponentController");
22676 exports.ComponentController = ComponentController_1.ComponentController;
22677 var Container_1 = require("./viewer/Container");
22678 exports.Container = Container_1.Container;
22679 var Observer_1 = require("./viewer/Observer");
22680 exports.Observer = Observer_1.Observer;
22681 var ImageSize_1 = require("./viewer/ImageSize");
22682 exports.ImageSize = ImageSize_1.ImageSize;
22683 var KeyboardService_1 = require("./viewer/KeyboardService");
22684 exports.KeyboardService = KeyboardService_1.KeyboardService;
22685 var LoadingService_1 = require("./viewer/LoadingService");
22686 exports.LoadingService = LoadingService_1.LoadingService;
22687 var MouseService_1 = require("./viewer/MouseService");
22688 exports.MouseService = MouseService_1.MouseService;
22689 var Navigator_1 = require("./viewer/Navigator");
22690 exports.Navigator = Navigator_1.Navigator;
22691 var PlayService_1 = require("./viewer/PlayService");
22692 exports.PlayService = PlayService_1.PlayService;
22693 var Projection_1 = require("./viewer/Projection");
22694 exports.Projection = Projection_1.Projection;
22695 var SpriteService_1 = require("./viewer/SpriteService");
22696 exports.SpriteService = SpriteService_1.SpriteService;
22697 var TouchService_1 = require("./viewer/TouchService");
22698 exports.TouchService = TouchService_1.TouchService;
22699 var Viewer_1 = require("./viewer/Viewer");
22700 exports.Viewer = Viewer_1.Viewer;
22702 },{"./viewer/Alignment":418,"./viewer/CacheService":419,"./viewer/ComponentController":420,"./viewer/Container":421,"./viewer/ImageSize":422,"./viewer/KeyboardService":423,"./viewer/LoadingService":424,"./viewer/MouseService":425,"./viewer/Navigator":426,"./viewer/Observer":427,"./viewer/PlayService":428,"./viewer/Projection":429,"./viewer/SpriteService":430,"./viewer/TouchService":431,"./viewer/Viewer":432}],293:[function(require,module,exports){
22704 /// <reference path="../../typings/index.d.ts" />
22705 Object.defineProperty(exports, "__esModule", { value: true });
22706 var Observable_1 = require("rxjs/Observable");
22707 require("rxjs/add/observable/defer");
22708 require("rxjs/add/observable/fromPromise");
22709 require("rxjs/add/operator/catch");
22710 require("rxjs/add/operator/map");
22711 var API_1 = require("../API");
22715 * @classdesc Provides methods for access of API v3.
22717 var APIv3 = /** @class */ (function () {
22719 * Create a new api v3 instance.
22721 * @param {number} clientId - Client id for API requests.
22722 * @param {number} [token] - Optional bearer token for API requests of
22723 * protected resources.
22724 * @param {ModelCreator} [creator] - Optional model creator instance.
22726 function APIv3(clientId, token, creator) {
22727 this._clientId = clientId;
22728 this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
22729 this._model = this._modelCreator.createModel(clientId, token);
22730 this._pageCount = 999;
22731 this._pathImageByKey = "imageByKey";
22732 this._pathImageCloseTo = "imageCloseTo";
22733 this._pathImagesByH = "imagesByH";
22734 this._pathImageViewAdd = "imageViewAdd";
22735 this._pathSequenceByKey = "sequenceByKey";
22736 this._pathSequenceViewAdd = "sequenceViewAdd";
22737 this._propertiesCore = [
22742 this._propertiesFill = [
22747 this._propertiesKey = [
22750 this._propertiesSequence = [
22753 this._propertiesSpatial = [
22767 this._propertiesUser = [
22771 APIv3.prototype.imageByKeyFill$ = function (keys) {
22772 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
22773 this._pathImageByKey,
22775 this._propertiesKey
22776 .concat(this._propertiesFill)
22777 .concat(this._propertiesSpatial),
22778 this._propertiesKey
22779 .concat(this._propertiesUser)
22781 .map(function (value) {
22783 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
22785 return value.json.imageByKey;
22786 }), this._pathImageByKey, keys);
22788 APIv3.prototype.imageByKeyFull$ = function (keys) {
22789 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
22790 this._pathImageByKey,
22792 this._propertiesKey
22793 .concat(this._propertiesCore)
22794 .concat(this._propertiesFill)
22795 .concat(this._propertiesSpatial),
22796 this._propertiesKey
22797 .concat(this._propertiesUser)
22799 .map(function (value) {
22801 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
22803 return value.json.imageByKey;
22804 }), this._pathImageByKey, keys);
22806 APIv3.prototype.imageCloseTo$ = function (lat, lon) {
22807 var lonLat = lon + ":" + lat;
22808 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
22809 this._pathImageCloseTo,
22811 this._propertiesKey
22812 .concat(this._propertiesCore)
22813 .concat(this._propertiesFill)
22814 .concat(this._propertiesSpatial),
22815 this._propertiesKey
22816 .concat(this._propertiesUser)
22818 .map(function (value) {
22819 return value != null ? value.json.imageCloseTo[lonLat] : null;
22820 }), this._pathImageCloseTo, [lonLat]);
22822 APIv3.prototype.imagesByH$ = function (hs) {
22824 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
22825 this._pathImagesByH,
22827 { from: 0, to: this._pageCount },
22828 this._propertiesKey
22829 .concat(this._propertiesCore),
22830 this._propertiesKey
22832 .map(function (value) {
22833 if (value == null) {
22834 value = { json: { imagesByH: {} } };
22835 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
22837 value.json.imagesByH[h] = {};
22838 for (var i = 0; i <= _this._pageCount; i++) {
22839 value.json.imagesByH[h][i] = null;
22843 return value.json.imagesByH;
22844 }), this._pathImagesByH, hs);
22846 APIv3.prototype.imageViewAdd$ = function (keys) {
22847 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
22849 APIv3.prototype.invalidateImageByKey = function (keys) {
22850 this._invalidateGet(this._pathImageByKey, keys);
22852 APIv3.prototype.invalidateImagesByH = function (hs) {
22853 this._invalidateGet(this._pathImagesByH, hs);
22855 APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
22856 this._invalidateGet(this._pathSequenceByKey, sKeys);
22858 APIv3.prototype.setToken = function (token) {
22859 this._model.invalidate([]);
22860 this._model = null;
22861 this._model = this._modelCreator.createModel(this._clientId, token);
22863 APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
22864 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
22865 this._pathSequenceByKey,
22867 this._propertiesKey
22868 .concat(this._propertiesSequence)
22870 .map(function (value) {
22871 return value.json.sequenceByKey;
22872 }), this._pathSequenceByKey, sequenceKeys);
22874 APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
22875 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
22877 Object.defineProperty(APIv3.prototype, "clientId", {
22879 return this._clientId;
22884 APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
22887 .catch(function (error) {
22888 _this._invalidateGet(path, paths);
22892 APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
22895 .catch(function (error) {
22896 _this._invalidateCall(path, paths);
22900 APIv3.prototype._invalidateGet = function (path, paths) {
22901 this._model.invalidate([path, paths]);
22903 APIv3.prototype._invalidateCall = function (path, paths) {
22904 this._model.invalidate([path], [paths]);
22906 APIv3.prototype._wrapPromise$ = function (promise) {
22907 return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
22911 exports.APIv3 = APIv3;
22912 exports.default = APIv3;
22914 },{"../API":280,"rxjs/Observable":29,"rxjs/add/observable/defer":39,"rxjs/add/observable/fromPromise":43,"rxjs/add/operator/catch":52,"rxjs/add/operator/map":65}],294:[function(require,module,exports){
22916 /// <reference path="../../typings/index.d.ts" />
22917 Object.defineProperty(exports, "__esModule", { value: true });
22918 var falcor = require("falcor");
22919 var HttpDataSource = require("falcor-http-datasource");
22920 var Utils_1 = require("../Utils");
22922 * @class ModelCreator
22924 * @classdesc Creates API models.
22926 var ModelCreator = /** @class */ (function () {
22927 function ModelCreator() {
22930 * Creates a Falcor model.
22932 * @description Max cache size will be set to 16 MB. Authorization
22933 * header will be added if bearer token is supplied.
22935 * @param {number} clientId - Client id for API requests.
22936 * @param {number} [token] - Optional bearer token for API requests of
22937 * protected resources.
22938 * @returns {falcor.Model} Falcor model for HTTP requests.
22940 ModelCreator.prototype.createModel = function (clientId, token) {
22941 var configuration = {
22943 withCredentials: false,
22945 if (token != null) {
22946 configuration.headers = { "Authorization": "Bearer " + token };
22948 return new falcor.Model({
22949 maxSize: 16 * 1024 * 1024,
22950 source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
22953 return ModelCreator;
22955 exports.ModelCreator = ModelCreator;
22956 exports.default = ModelCreator;
22958 },{"../Utils":291,"falcor":15,"falcor-http-datasource":10}],295:[function(require,module,exports){
22960 /// <reference path="../../typings/index.d.ts" />
22961 var __extends = (this && this.__extends) || (function () {
22962 var extendStatics = Object.setPrototypeOf ||
22963 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22964 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22965 return function (d, b) {
22966 extendStatics(d, b);
22967 function __() { this.constructor = d; }
22968 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22971 Object.defineProperty(exports, "__esModule", { value: true });
22972 var vd = require("virtual-dom");
22973 var Component_1 = require("../Component");
22974 var AttributionComponent = /** @class */ (function (_super) {
22975 __extends(AttributionComponent, _super);
22976 function AttributionComponent(name, container, navigator) {
22977 return _super.call(this, name, container, navigator) || this;
22979 AttributionComponent.prototype._activate = function () {
22981 this._disposable = this._navigator.stateService.currentNode$
22982 .map(function (node) {
22983 return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
22985 .subscribe(this._container.domRenderer.render$);
22987 AttributionComponent.prototype._deactivate = function () {
22988 this._disposable.unsubscribe();
22990 AttributionComponent.prototype._getDefaultConfiguration = function () {
22993 AttributionComponent.prototype._getAttributionNode = function (username, key) {
22994 return vd.h("div.Attribution", {}, [
22995 vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
22997 textContent: "@" + username,
22999 vd.h("span", { textContent: "|" }, []),
23000 vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + key + "&focus=photo",
23002 textContent: "mapillary.com",
23006 AttributionComponent.componentName = "attribution";
23007 return AttributionComponent;
23008 }(Component_1.Component));
23009 exports.AttributionComponent = AttributionComponent;
23010 Component_1.ComponentService.register(AttributionComponent);
23011 exports.default = AttributionComponent;
23013 },{"../Component":281,"virtual-dom":237}],296:[function(require,module,exports){
23015 /// <reference path="../../typings/index.d.ts" />
23016 var __extends = (this && this.__extends) || (function () {
23017 var extendStatics = Object.setPrototypeOf ||
23018 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23019 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23020 return function (d, b) {
23021 extendStatics(d, b);
23022 function __() { this.constructor = d; }
23023 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23026 Object.defineProperty(exports, "__esModule", { value: true });
23027 var vd = require("virtual-dom");
23028 var Component_1 = require("../Component");
23029 var BackgroundComponent = /** @class */ (function (_super) {
23030 __extends(BackgroundComponent, _super);
23031 function BackgroundComponent(name, container, navigator) {
23032 return _super.call(this, name, container, navigator) || this;
23034 BackgroundComponent.prototype._activate = function () {
23035 this._container.domRenderer.render$
23036 .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given image.") });
23038 BackgroundComponent.prototype._deactivate = function () {
23041 BackgroundComponent.prototype._getDefaultConfiguration = function () {
23044 BackgroundComponent.prototype._getBackgroundNode = function (notice) {
23045 // todo: add condition for when to display the DOM node
23046 return vd.h("div.BackgroundWrapper", {}, [
23047 vd.h("p", { textContent: notice }, []),
23050 BackgroundComponent.componentName = "background";
23051 return BackgroundComponent;
23052 }(Component_1.Component));
23053 exports.BackgroundComponent = BackgroundComponent;
23054 Component_1.ComponentService.register(BackgroundComponent);
23055 exports.default = BackgroundComponent;
23057 },{"../Component":281,"virtual-dom":237}],297:[function(require,module,exports){
23059 /// <reference path="../../typings/index.d.ts" />
23060 var __extends = (this && this.__extends) || (function () {
23061 var extendStatics = Object.setPrototypeOf ||
23062 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23063 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23064 return function (d, b) {
23065 extendStatics(d, b);
23066 function __() { this.constructor = d; }
23067 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23070 Object.defineProperty(exports, "__esModule", { value: true });
23071 var vd = require("virtual-dom");
23072 var Observable_1 = require("rxjs/Observable");
23073 var Component_1 = require("../Component");
23074 var Geo_1 = require("../Geo");
23075 var BearingComponent = /** @class */ (function (_super) {
23076 __extends(BearingComponent, _super);
23077 function BearingComponent(name, container, navigator) {
23078 var _this = _super.call(this, name, container, navigator) || this;
23079 _this._spatial = new Geo_1.Spatial();
23080 _this._svgNamespace = "http://www.w3.org/2000/svg";
23081 _this._distinctThreshold = Math.PI / 90;
23084 BearingComponent.prototype._activate = function () {
23086 var nodeBearingFov$ = this._navigator.stateService.currentState$
23087 .distinctUntilChanged(undefined, function (frame) {
23088 return frame.state.currentNode.key;
23090 .map(function (frame) {
23091 var node = frame.state.currentNode;
23092 var transform = frame.state.currentTransform;
23094 var panoHFov = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
23095 return [_this._spatial.degToRad(node.ca), panoHFov];
23097 var size = Math.max(transform.basicWidth, transform.basicHeight);
23099 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
23100 "Not showing available fov.");
23102 var hFov = size > 0 ?
23103 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
23105 return [_this._spatial.degToRad(node.ca), hFov];
23107 .distinctUntilChanged(function (a1, a2) {
23108 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
23109 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
23111 var cameraBearingFov$ = this._container.renderService.renderCamera$
23112 .map(function (rc) {
23113 var vFov = _this._spatial.degToRad(rc.perspective.fov);
23114 var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
23116 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
23117 return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
23119 .distinctUntilChanged(function (a1, a2) {
23120 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
23121 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
23123 this._renderSubscription = Observable_1.Observable
23124 .combineLatest(nodeBearingFov$, cameraBearingFov$)
23125 .map(function (args) {
23126 var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
23127 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
23128 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
23130 var north = vd.h("div.BearingIndicatorNorth", {}, []);
23131 var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
23132 var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
23133 var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
23136 vnode: vd.h("div.BearingIndicator", {}, [
23143 .subscribe(this._container.domRenderer.render$);
23145 BearingComponent.prototype._deactivate = function () {
23146 this._renderSubscription.unsubscribe();
23148 BearingComponent.prototype._getDefaultConfiguration = function () {
23151 BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
23152 var group = vd.h("g", {
23153 attributes: { transform: "translate(1,1)" },
23154 namespace: this._svgNamespace,
23155 }, [nodeSector, cameraSector]);
23156 var centerCircle = vd.h("circle", {
23163 "stroke-width": "0.0833333",
23165 namespace: this._svgNamespace,
23167 var svg = vd.h("svg", {
23168 attributes: { viewBox: "0 0 2 2" },
23169 namespace: this._svgNamespace,
23174 position: "absolute",
23177 }, [group, centerCircle]);
23180 BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
23181 if (fov > 2 * Math.PI - Math.PI / 90) {
23182 return vd.h("circle", {
23183 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
23184 namespace: this._svgNamespace,
23187 var arcStart = bearing - fov / 2 - Math.PI / 2;
23188 var arcEnd = arcStart + fov;
23189 var startX = Math.cos(arcStart);
23190 var startY = Math.sin(arcStart);
23191 var endX = Math.cos(arcEnd);
23192 var endY = Math.sin(arcEnd);
23193 var largeArc = fov >= Math.PI ? 1 : 0;
23194 var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
23195 return vd.h("path", {
23196 attributes: { d: description, fill: fill },
23197 namespace: this._svgNamespace,
23200 BearingComponent.componentName = "bearing";
23201 return BearingComponent;
23202 }(Component_1.Component));
23203 exports.BearingComponent = BearingComponent;
23204 Component_1.ComponentService.register(BearingComponent);
23205 exports.default = BearingComponent;
23207 },{"../Component":281,"../Geo":284,"rxjs/Observable":29,"virtual-dom":237}],298:[function(require,module,exports){
23209 var __extends = (this && this.__extends) || (function () {
23210 var extendStatics = Object.setPrototypeOf ||
23211 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23212 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23213 return function (d, b) {
23214 extendStatics(d, b);
23215 function __() { this.constructor = d; }
23216 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23219 Object.defineProperty(exports, "__esModule", { value: true });
23220 var Observable_1 = require("rxjs/Observable");
23221 require("rxjs/add/observable/combineLatest");
23222 require("rxjs/add/observable/from");
23223 require("rxjs/add/observable/merge");
23224 require("rxjs/add/observable/of");
23225 require("rxjs/add/observable/zip");
23226 require("rxjs/add/operator/catch");
23227 require("rxjs/add/operator/combineLatest");
23228 require("rxjs/add/operator/distinct");
23229 require("rxjs/add/operator/expand");
23230 require("rxjs/add/operator/filter");
23231 require("rxjs/add/operator/map");
23232 require("rxjs/add/operator/merge");
23233 require("rxjs/add/operator/mergeMap");
23234 require("rxjs/add/operator/mergeAll");
23235 require("rxjs/add/operator/skip");
23236 require("rxjs/add/operator/switchMap");
23237 var Edge_1 = require("../Edge");
23238 var Component_1 = require("../Component");
23239 var CacheComponent = /** @class */ (function (_super) {
23240 __extends(CacheComponent, _super);
23241 function CacheComponent(name, container, navigator) {
23242 return _super.call(this, name, container, navigator) || this;
23245 * Set the cache depth.
23247 * Configures the cache depth. The cache depth can be different for
23248 * different edge direction types.
23250 * @param {ICacheDepth} depth - Cache depth structure.
23252 CacheComponent.prototype.setDepth = function (depth) {
23253 this.configure({ depth: depth });
23255 CacheComponent.prototype._activate = function () {
23257 this._sequenceSubscription = Observable_1.Observable
23258 .combineLatest(this._navigator.stateService.currentNode$
23259 .switchMap(function (node) {
23260 return node.sequenceEdges$;
23262 .filter(function (status) {
23263 return status.cached;
23264 }), this._configuration$)
23265 .switchMap(function (nc) {
23266 var status = nc[0];
23267 var configuration = nc[1];
23268 var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
23269 var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
23270 var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
23271 return Observable_1.Observable
23272 .merge(next$, prev$)
23273 .catch(function (error, caught) {
23274 console.error("Failed to cache sequence edges.", error);
23275 return Observable_1.Observable.empty();
23278 .subscribe(function () { });
23279 this._spatialSubscription = this._navigator.stateService.currentNode$
23280 .switchMap(function (node) {
23281 return Observable_1.Observable
23282 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
23283 .filter(function (status) {
23284 return status.cached;
23287 .combineLatest(this._configuration$, function (ns, configuration) {
23288 return [ns[0], ns[1], configuration];
23290 .switchMap(function (args) {
23291 var node = args[0];
23292 var edges = args[1].edges;
23293 var depth = args[2].depth;
23294 var panoDepth = Math.max(0, Math.min(2, depth.pano));
23295 var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
23296 var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
23297 var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
23298 var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
23299 var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
23300 var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
23301 var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
23302 var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
23303 var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
23304 var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
23305 return Observable_1.Observable
23306 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
23307 .catch(function (error, caught) {
23308 console.error("Failed to cache spatial edges.", error);
23309 return Observable_1.Observable.empty();
23312 .subscribe(function () { });
23314 CacheComponent.prototype._deactivate = function () {
23315 this._sequenceSubscription.unsubscribe();
23316 this._spatialSubscription.unsubscribe();
23318 CacheComponent.prototype._getDefaultConfiguration = function () {
23319 return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
23321 CacheComponent.prototype._cache$ = function (edges, direction, depth) {
23323 return Observable_1.Observable
23324 .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
23325 .expand(function (ed) {
23328 var edgesDepths$ = [];
23330 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
23331 var edge = es_1[_i];
23332 if (edge.data.direction === direction) {
23333 edgesDepths$.push(Observable_1.Observable
23334 .zip(_this._navigator.graphService.cacheNode$(edge.to)
23335 .mergeMap(function (n) {
23336 return _this._nodeToEdges$(n, direction);
23337 }), Observable_1.Observable.of(d - 1)));
23341 return Observable_1.Observable
23342 .from(edgesDepths$)
23347 CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
23348 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
23349 node.sequenceEdges$ :
23350 node.spatialEdges$)
23351 .first(function (status) {
23352 return status.cached;
23354 .map(function (status) {
23355 return status.edges;
23358 CacheComponent.componentName = "cache";
23359 return CacheComponent;
23360 }(Component_1.Component));
23361 exports.CacheComponent = CacheComponent;
23362 Component_1.ComponentService.register(CacheComponent);
23363 exports.default = CacheComponent;
23365 },{"../Component":281,"../Edge":282,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/from":41,"rxjs/add/observable/merge":44,"rxjs/add/observable/of":45,"rxjs/add/observable/zip":48,"rxjs/add/operator/catch":52,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinct":57,"rxjs/add/operator/expand":60,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeAll":67,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/skip":77,"rxjs/add/operator/switchMap":81}],299:[function(require,module,exports){
23367 var __extends = (this && this.__extends) || (function () {
23368 var extendStatics = Object.setPrototypeOf ||
23369 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23370 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23371 return function (d, b) {
23372 extendStatics(d, b);
23373 function __() { this.constructor = d; }
23374 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23377 Object.defineProperty(exports, "__esModule", { value: true });
23378 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
23379 var Subject_1 = require("rxjs/Subject");
23380 require("rxjs/add/operator/publishReplay");
23381 require("rxjs/add/operator/scan");
23382 require("rxjs/add/operator/startWith");
23383 var Utils_1 = require("../Utils");
23384 var Component = /** @class */ (function (_super) {
23385 __extends(Component, _super);
23386 function Component(name, container, navigator) {
23387 var _this = _super.call(this) || this;
23388 _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
23389 _this._configurationSubject$ = new Subject_1.Subject();
23390 _this._activated = false;
23391 _this._container = container;
23392 _this._name = name;
23393 _this._navigator = navigator;
23394 _this._configuration$ =
23395 _this._configurationSubject$
23396 .startWith(_this.defaultConfiguration)
23397 .scan(function (conf, newConf) {
23398 for (var key in newConf) {
23399 if (newConf.hasOwnProperty(key)) {
23400 conf[key] = newConf[key];
23407 _this._configuration$.subscribe(function () { });
23410 Object.defineProperty(Component.prototype, "activated", {
23412 return this._activated;
23417 Object.defineProperty(Component.prototype, "activated$", {
23419 return this._activated$;
23424 Object.defineProperty(Component.prototype, "defaultConfiguration", {
23426 * Get default configuration.
23428 * @returns {TConfiguration} Default configuration for component.
23431 return this._getDefaultConfiguration();
23436 Object.defineProperty(Component.prototype, "configuration$", {
23438 return this._configuration$;
23443 Object.defineProperty(Component.prototype, "name", {
23450 Component.prototype.activate = function (conf) {
23451 if (this._activated) {
23454 if (conf !== undefined) {
23455 this._configurationSubject$.next(conf);
23457 this._activated = true;
23459 this._activated$.next(true);
23461 Component.prototype.configure = function (conf) {
23462 this._configurationSubject$.next(conf);
23464 Component.prototype.deactivate = function () {
23465 if (!this._activated) {
23468 this._activated = false;
23469 this._deactivate();
23470 this._container.domRenderer.clear(this._name);
23471 this._container.glRenderer.clear(this._name);
23472 this._activated$.next(false);
23475 * Detect the viewer's new width and height and resize the component's
23476 * rendered elements accordingly if applicable.
23478 Component.prototype.resize = function () { return; };
23480 * Component name. Used when interacting with component through the Viewer's API.
23482 Component.componentName = "not_worthy";
23484 }(Utils_1.EventEmitter));
23485 exports.Component = Component;
23486 exports.default = Component;
23488 },{"../Utils":291,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/startWith":80}],300:[function(require,module,exports){
23490 /// <reference path="../../typings/index.d.ts" />
23491 Object.defineProperty(exports, "__esModule", { value: true });
23492 var _ = require("underscore");
23493 var Error_1 = require("../Error");
23494 var ComponentService = /** @class */ (function () {
23495 function ComponentService(container, navigator) {
23496 this._components = {};
23497 for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
23498 var component = _a[_i];
23499 this._components[component.componentName] = {
23501 component: new component(component.componentName, container, navigator),
23504 this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
23505 this._coverComponent.activate();
23506 this._coverActivated = true;
23508 ComponentService.register = function (component) {
23509 if (ComponentService.registeredComponents[component.componentName] === undefined) {
23510 ComponentService.registeredComponents[component.componentName] = component;
23513 ComponentService.registerCover = function (coverComponent) {
23514 ComponentService.registeredCoverComponent = coverComponent;
23516 Object.defineProperty(ComponentService.prototype, "coverActivated", {
23518 return this._coverActivated;
23523 ComponentService.prototype.activateCover = function () {
23524 if (this._coverActivated) {
23527 this._coverActivated = true;
23528 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
23529 var component = _a[_i];
23530 if (component.active) {
23531 component.component.deactivate();
23536 ComponentService.prototype.deactivateCover = function () {
23537 if (!this._coverActivated) {
23540 this._coverActivated = false;
23541 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
23542 var component = _a[_i];
23543 if (component.active) {
23544 component.component.activate();
23549 ComponentService.prototype.activate = function (name) {
23550 this._checkName(name);
23551 this._components[name].active = true;
23552 if (!this._coverActivated) {
23553 this.get(name).activate();
23556 ComponentService.prototype.configure = function (name, conf) {
23557 this._checkName(name);
23558 this.get(name).configure(conf);
23560 ComponentService.prototype.deactivate = function (name) {
23561 this._checkName(name);
23562 this._components[name].active = false;
23563 if (!this._coverActivated) {
23564 this.get(name).deactivate();
23567 ComponentService.prototype.resize = function () {
23568 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
23569 var component = _a[_i];
23570 component.component.resize();
23573 ComponentService.prototype.get = function (name) {
23574 return this._components[name].component;
23576 ComponentService.prototype.getCover = function () {
23577 return this._coverComponent;
23579 ComponentService.prototype._checkName = function (name) {
23580 if (!(name in this._components)) {
23581 throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
23584 ComponentService.registeredComponents = {};
23585 return ComponentService;
23587 exports.ComponentService = ComponentService;
23588 exports.default = ComponentService;
23590 },{"../Error":283,"underscore":233}],301:[function(require,module,exports){
23592 /// <reference path="../../typings/index.d.ts" />
23593 var __extends = (this && this.__extends) || (function () {
23594 var extendStatics = Object.setPrototypeOf ||
23595 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23596 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23597 return function (d, b) {
23598 extendStatics(d, b);
23599 function __() { this.constructor = d; }
23600 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23603 Object.defineProperty(exports, "__esModule", { value: true });
23604 var vd = require("virtual-dom");
23605 require("rxjs/add/operator/filter");
23606 require("rxjs/add/operator/map");
23607 require("rxjs/add/operator/withLatestFrom");
23608 var Component_1 = require("../Component");
23609 var CoverComponent = /** @class */ (function (_super) {
23610 __extends(CoverComponent, _super);
23611 function CoverComponent(name, container, navigator) {
23612 return _super.call(this, name, container, navigator) || this;
23614 CoverComponent.prototype._activate = function () {
23616 this._keyDisposable = this._navigator.stateService.currentNode$
23617 .withLatestFrom(this._configuration$, function (node, configuration) {
23618 return [node, configuration];
23620 .filter(function (_a) {
23621 var node = _a[0], configuration = _a[1];
23622 return node.key !== configuration.key;
23624 .map(function (_a) {
23625 var node = _a[0], configuration = _a[1];
23628 .map(function (node) {
23629 return { key: node.key, src: node.image.src };
23631 .subscribe(this._configurationSubject$);
23632 this._disposable = this._configuration$
23633 .map(function (conf) {
23635 return { name: _this._name, vnode: vd.h("div", []) };
23637 if (conf.state === Component_1.CoverState.Hidden) {
23638 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
23640 return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
23642 .subscribe(this._container.domRenderer.render$);
23644 CoverComponent.prototype._deactivate = function () {
23645 this._disposable.unsubscribe();
23646 this._keyDisposable.unsubscribe();
23648 CoverComponent.prototype._getDefaultConfiguration = function () {
23649 return { state: Component_1.CoverState.Visible };
23651 CoverComponent.prototype._getCoverButtonVNode = function (conf) {
23653 var cover = conf.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
23654 return vd.h(cover, [
23655 this._getCoverBackgroundVNode(conf),
23656 vd.h("button.CoverButton", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, ["Explore"]),
23657 vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
23660 CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
23661 var url = conf.src != null ?
23662 "url(" + conf.src + ")" :
23663 "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
23664 var properties = { style: { backgroundImage: url } };
23666 if (conf.state === Component_1.CoverState.Loading) {
23667 children.push(vd.h("div.Spinner", {}, []));
23669 children.push(vd.h("div.CoverBackgroundGradient", {}, []));
23670 return vd.h("div.CoverBackground", properties, children);
23672 CoverComponent.componentName = "cover";
23673 return CoverComponent;
23674 }(Component_1.Component));
23675 exports.CoverComponent = CoverComponent;
23676 Component_1.ComponentService.registerCover(CoverComponent);
23677 exports.default = CoverComponent;
23679 },{"../Component":281,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":87,"virtual-dom":237}],302:[function(require,module,exports){
23681 /// <reference path="../../typings/index.d.ts" />
23682 var __extends = (this && this.__extends) || (function () {
23683 var extendStatics = Object.setPrototypeOf ||
23684 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23685 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23686 return function (d, b) {
23687 extendStatics(d, b);
23688 function __() { this.constructor = d; }
23689 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23692 Object.defineProperty(exports, "__esModule", { value: true });
23693 var _ = require("underscore");
23694 var vd = require("virtual-dom");
23695 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
23696 require("rxjs/add/operator/combineLatest");
23697 var Component_1 = require("../Component");
23698 var DebugComponent = /** @class */ (function (_super) {
23699 __extends(DebugComponent, _super);
23700 function DebugComponent() {
23701 var _this = _super !== null && _super.apply(this, arguments) || this;
23702 _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
23705 DebugComponent.prototype._activate = function () {
23707 this._disposable = this._navigator.stateService.currentState$
23708 .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
23709 return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
23711 .subscribe(this._container.domRenderer.render$);
23713 DebugComponent.prototype._deactivate = function () {
23714 this._disposable.unsubscribe();
23716 DebugComponent.prototype._getDefaultConfiguration = function () {
23719 DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
23721 ret.push(vd.h("h2", "Node"));
23722 if (frame.state.currentNode) {
23723 ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
23725 if (frame.state.previousNode) {
23726 ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
23728 ret.push(vd.h("h2", "Loading"));
23732 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
23733 var loadStat = _a[_i];
23734 total += loadStat.loaded;
23735 if (loadStat.loaded !== loadStat.total) {
23742 ret.push(vd.h("p", "Loaded Images: " + loaded));
23743 ret.push(vd.h("p", "Loading Images: " + loading));
23744 ret.push(vd.h("p", "Total bytes loaded: " + total));
23745 ret.push(vd.h("h2", "Camera"));
23746 ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
23747 ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
23748 ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
23749 ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
23750 ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
23751 ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
23752 ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
23753 ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
23754 ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
23757 DebugComponent.prototype._getDebugVNode = function (open, info) {
23759 return vd.h("div.Debug", {}, [
23760 vd.h("h2", {}, ["Debug"]),
23761 this._getDebugVNodeButton(open),
23762 vd.h("pre", {}, info),
23766 return this._getDebugVNodeButton(open);
23769 DebugComponent.prototype._getDebugVNodeButton = function (open) {
23770 var buttonText = open ? "Disable Debug" : "D";
23771 var buttonCssClass = open ? "" : ".DebugButtonFixed";
23773 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
23776 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
23779 DebugComponent.prototype._closeDebugElement = function (open) {
23780 this._open$.next(false);
23782 DebugComponent.prototype._openDebugElement = function () {
23783 this._open$.next(true);
23785 DebugComponent.componentName = "debug";
23786 return DebugComponent;
23787 }(Component_1.Component));
23788 exports.DebugComponent = DebugComponent;
23789 Component_1.ComponentService.register(DebugComponent);
23790 exports.default = DebugComponent;
23792 },{"../Component":281,"rxjs/BehaviorSubject":26,"rxjs/add/operator/combineLatest":53,"underscore":233,"virtual-dom":237}],303:[function(require,module,exports){
23794 /// <reference path="../../typings/index.d.ts" />
23795 var __extends = (this && this.__extends) || (function () {
23796 var extendStatics = Object.setPrototypeOf ||
23797 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23798 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23799 return function (d, b) {
23800 extendStatics(d, b);
23801 function __() { this.constructor = d; }
23802 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23805 Object.defineProperty(exports, "__esModule", { value: true });
23806 var vd = require("virtual-dom");
23807 var Observable_1 = require("rxjs/Observable");
23808 require("rxjs/add/operator/combineLatest");
23809 var Component_1 = require("../Component");
23810 var Utils_1 = require("../Utils");
23811 var ImageComponent = /** @class */ (function (_super) {
23812 __extends(ImageComponent, _super);
23813 function ImageComponent(name, container, navigator, dom) {
23814 var _this = _super.call(this, name, container, navigator) || this;
23815 _this._canvasId = container.id + "-" + _this._name;
23816 _this._dom = !!dom ? dom : new Utils_1.DOM();
23819 ImageComponent.prototype._activate = function () {
23821 var canvasSize$ = this._container.domRenderer.element$
23822 .map(function (element) {
23823 return _this._dom.document.getElementById(_this._canvasId);
23825 .filter(function (canvas) {
23828 .map(function (canvas) {
23829 var adaptableDomRenderer = canvas.parentElement;
23830 var width = adaptableDomRenderer.offsetWidth;
23831 var height = adaptableDomRenderer.offsetHeight;
23832 return [canvas, { height: height, width: width }];
23834 .distinctUntilChanged(function (s1, s2) {
23835 return s1.height === s2.height && s1.width === s2.width;
23837 var canvas = _a[0], size = _a[1];
23840 this.drawSubscription = Observable_1.Observable
23841 .combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
23842 .subscribe(function (_a) {
23843 var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
23844 canvas.width = size.width;
23845 canvas.height = size.height;
23848 .drawImage(node.image, 0, 0, size.width, size.height);
23850 this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
23852 ImageComponent.prototype._deactivate = function () {
23853 this.drawSubscription.unsubscribe();
23855 ImageComponent.prototype._getDefaultConfiguration = function () {
23858 ImageComponent.componentName = "image";
23859 return ImageComponent;
23860 }(Component_1.Component));
23861 exports.ImageComponent = ImageComponent;
23862 Component_1.ComponentService.register(ImageComponent);
23863 exports.default = ImageComponent;
23865 },{"../Component":281,"../Utils":291,"rxjs/Observable":29,"rxjs/add/operator/combineLatest":53,"virtual-dom":237}],304:[function(require,module,exports){
23867 /// <reference path="../../typings/index.d.ts" />
23868 var __extends = (this && this.__extends) || (function () {
23869 var extendStatics = Object.setPrototypeOf ||
23870 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23871 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23872 return function (d, b) {
23873 extendStatics(d, b);
23874 function __() { this.constructor = d; }
23875 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23878 Object.defineProperty(exports, "__esModule", { value: true });
23879 var _ = require("underscore");
23880 var vd = require("virtual-dom");
23881 var Observable_1 = require("rxjs/Observable");
23882 require("rxjs/add/operator/combineLatest");
23883 var Component_1 = require("../Component");
23884 var LoadingComponent = /** @class */ (function (_super) {
23885 __extends(LoadingComponent, _super);
23886 function LoadingComponent(name, container, navigator) {
23887 return _super.call(this, name, container, navigator) || this;
23889 LoadingComponent.prototype._activate = function () {
23891 this._loadingSubscription = this._navigator.loadingService.loading$
23892 .switchMap(function (loading) {
23894 _this._navigator.imageLoadingService.loadstatus$ :
23895 Observable_1.Observable.of({});
23897 .map(function (loadStatus) {
23900 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
23901 var loadStat = _a[_i];
23902 if (loadStat.loaded !== loadStat.total) {
23903 loaded += loadStat.loaded;
23904 total += loadStat.total;
23907 var percentage = 100;
23909 percentage = (loaded / total) * 100;
23911 return { name: _this._name, vnode: _this._getBarVNode(percentage) };
23913 .subscribe(this._container.domRenderer.render$);
23915 LoadingComponent.prototype._deactivate = function () {
23916 this._loadingSubscription.unsubscribe();
23918 LoadingComponent.prototype._getDefaultConfiguration = function () {
23921 LoadingComponent.prototype._getBarVNode = function (percentage) {
23922 var loadingBarStyle = {};
23923 var loadingContainerStyle = {};
23924 if (percentage !== 100) {
23925 loadingBarStyle.width = percentage.toFixed(0) + "%";
23926 loadingBarStyle.opacity = "1";
23929 loadingBarStyle.width = "100%";
23930 loadingBarStyle.opacity = "0";
23932 return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
23934 LoadingComponent.componentName = "loading";
23935 return LoadingComponent;
23936 }(Component_1.Component));
23937 exports.LoadingComponent = LoadingComponent;
23938 Component_1.ComponentService.register(LoadingComponent);
23939 exports.default = LoadingComponent;
23941 },{"../Component":281,"rxjs/Observable":29,"rxjs/add/operator/combineLatest":53,"underscore":233,"virtual-dom":237}],305:[function(require,module,exports){
23943 /// <reference path="../../typings/index.d.ts" />
23944 var __extends = (this && this.__extends) || (function () {
23945 var extendStatics = Object.setPrototypeOf ||
23946 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23947 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23948 return function (d, b) {
23949 extendStatics(d, b);
23950 function __() { this.constructor = d; }
23951 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23954 Object.defineProperty(exports, "__esModule", { value: true });
23955 var vd = require("virtual-dom");
23956 var Observable_1 = require("rxjs/Observable");
23957 require("rxjs/add/operator/map");
23958 require("rxjs/add/operator/first");
23959 var Edge_1 = require("../Edge");
23960 var Component_1 = require("../Component");
23962 * @class NavigationComponent
23964 * @classdesc Fallback navigation component for environments without WebGL support.
23966 * Replaces the functionality in the Direction and Sequence components.
23968 var NavigationComponent = /** @class */ (function (_super) {
23969 __extends(NavigationComponent, _super);
23970 function NavigationComponent(name, container, navigator) {
23971 var _this = _super.call(this, name, container, navigator) || this;
23972 _this._seqNames = {};
23973 _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
23974 _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
23975 _this._spaTopNames = {};
23976 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
23977 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
23978 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
23979 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
23980 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
23981 _this._spaBottomNames = {};
23982 _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
23983 _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
23986 NavigationComponent.prototype._activate = function () {
23988 this._renderSubscription = Observable_1.Observable
23989 .combineLatest(this._navigator.stateService.currentNode$, this._configuration$)
23990 .switchMap(function (_a) {
23991 var node = _a[0], configuration = _a[1];
23992 var sequenceEdges$ = configuration.sequence ?
23993 node.sequenceEdges$
23994 .map(function (status) {
23995 return status.edges
23996 .map(function (edge) {
23997 return edge.data.direction;
24000 Observable_1.Observable.of([]);
24001 var spatialEdges$ = !node.pano && configuration.spatial ?
24003 .map(function (status) {
24004 return status.edges
24005 .map(function (edge) {
24006 return edge.data.direction;
24009 Observable_1.Observable.of([]);
24010 return Observable_1.Observable
24011 .combineLatest(sequenceEdges$, spatialEdges$)
24012 .map(function (_a) {
24013 var seq = _a[0], spa = _a[1];
24014 return seq.concat(spa);
24017 .map(function (edgeDirections) {
24018 var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
24019 var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
24020 var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
24021 var seqContainer = vd.h("div.NavigationSequence", seqs);
24022 var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
24023 var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
24024 var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
24025 return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
24027 .subscribe(this._container.domRenderer.render$);
24029 NavigationComponent.prototype._deactivate = function () {
24030 this._renderSubscription.unsubscribe();
24032 NavigationComponent.prototype._getDefaultConfiguration = function () {
24033 return { sequence: true, spatial: true };
24035 NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
24037 for (var arrowName in arrowNames) {
24038 if (!(arrowNames.hasOwnProperty(arrowName))) {
24041 var direction = Edge_1.EdgeDirection[arrowName];
24042 if (edgeDirections.indexOf(direction) !== -1) {
24043 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
24046 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
24051 NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
24053 return vd.h("span.Direction.Direction" + name, {
24054 onclick: function (ev) {
24055 _this._navigator.moveDir$(direction)
24056 .subscribe(function (node) { return; }, function (error) { console.error(error); });
24059 visibility: visibility,
24063 NavigationComponent.componentName = "navigation";
24064 return NavigationComponent;
24065 }(Component_1.Component));
24066 exports.NavigationComponent = NavigationComponent;
24067 Component_1.ComponentService.register(NavigationComponent);
24068 exports.default = NavigationComponent;
24070 },{"../Component":281,"../Edge":282,"rxjs/Observable":29,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"virtual-dom":237}],306:[function(require,module,exports){
24072 /// <reference path="../../typings/index.d.ts" />
24073 var __extends = (this && this.__extends) || (function () {
24074 var extendStatics = Object.setPrototypeOf ||
24075 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24076 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24077 return function (d, b) {
24078 extendStatics(d, b);
24079 function __() { this.constructor = d; }
24080 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24083 Object.defineProperty(exports, "__esModule", { value: true });
24084 var _ = require("underscore");
24085 var vd = require("virtual-dom");
24086 var Observable_1 = require("rxjs/Observable");
24087 require("rxjs/add/observable/fromPromise");
24088 require("rxjs/add/observable/of");
24089 require("rxjs/add/operator/combineLatest");
24090 require("rxjs/add/operator/distinct");
24091 require("rxjs/add/operator/distinctUntilChanged");
24092 require("rxjs/add/operator/filter");
24093 require("rxjs/add/operator/map");
24094 require("rxjs/add/operator/mergeMap");
24095 require("rxjs/add/operator/pluck");
24096 require("rxjs/add/operator/scan");
24097 var Component_1 = require("../Component");
24098 var DescriptionState = /** @class */ (function () {
24099 function DescriptionState() {
24101 return DescriptionState;
24103 var RouteState = /** @class */ (function () {
24104 function RouteState() {
24108 var RouteTrack = /** @class */ (function () {
24109 function RouteTrack() {
24110 this.nodeInstructions = [];
24111 this.nodeInstructionsOrdered = [];
24115 var RouteComponent = /** @class */ (function (_super) {
24116 __extends(RouteComponent, _super);
24117 function RouteComponent(name, container, navigator) {
24118 return _super.call(this, name, container, navigator) || this;
24120 RouteComponent.prototype._activate = function () {
24122 var _slowedStream$;
24123 _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
24124 return (frame.id % 2) === 0;
24125 }).filter(function (frame) {
24126 return frame.state.nodesAhead < 15;
24127 }).distinctUntilChanged(undefined, function (frame) {
24128 return frame.state.lastNode.key;
24131 _routeTrack$ = this.configuration$.mergeMap(function (conf) {
24132 return Observable_1.Observable.from(conf.paths);
24133 }).distinct(function (p) {
24134 return p.sequenceKey;
24135 }).mergeMap(function (path) {
24136 return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
24137 .map(function (sequenceByKey) {
24138 return sequenceByKey[path.sequenceKey];
24140 }).combineLatest(this.configuration$, function (sequence, conf) {
24142 var instructionPlaces = [];
24143 for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
24145 if (path.sequenceKey === sequence.key) {
24146 var nodeInstructions = [];
24147 var saveKey = false;
24148 for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
24150 if (path.startKey === key) {
24154 var description = null;
24155 for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
24156 var infoKey = _e[_d];
24157 if (infoKey.key === key) {
24158 description = infoKey.description;
24161 nodeInstructions.push({ description: description, key: key });
24163 if (path.stopKey === key) {
24167 instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
24171 return instructionPlaces;
24172 }).scan(function (routeTrack, instructionPlaces) {
24173 for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
24174 var instructionPlace = instructionPlaces_1[_i];
24175 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
24177 routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
24179 }, new RouteTrack());
24180 this._disposable = _slowedStream$
24181 .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
24182 return { conf: conf, frame: frame, routeTrack: routeTrack };
24183 }).scan(function (routeState, rtAndFrame) {
24184 if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
24185 routeState.routeTrack = rtAndFrame.routeTrack;
24186 routeState.currentNode = rtAndFrame.frame.state.currentNode;
24187 routeState.lastNode = rtAndFrame.frame.state.lastNode;
24188 routeState.playing = true;
24191 _this._navigator.stateService.cutNodes();
24192 routeState.playing = false;
24195 }, new RouteState())
24196 .filter(function (routeState) {
24197 return routeState.playing;
24198 }).filter(function (routeState) {
24199 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24200 var nodeInstruction = _a[_i];
24201 if (!nodeInstruction) {
24204 if (nodeInstruction.key === routeState.lastNode.key) {
24209 }).distinctUntilChanged(undefined, function (routeState) {
24210 return routeState.lastNode.key;
24211 }).mergeMap(function (routeState) {
24213 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24214 var nodeInstruction = _a[_i];
24215 if (nodeInstruction.key === routeState.lastNode.key) {
24220 var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
24221 if (!nextInstruction) {
24222 return Observable_1.Observable.of(null);
24224 return _this._navigator.graphService.cacheNode$(nextInstruction.key);
24225 }).combineLatest(this.configuration$, function (node, conf) {
24226 return { conf: conf, node: node };
24227 }).filter(function (cAN) {
24228 return cAN.node !== null && cAN.conf.playing;
24229 }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
24230 this._disposableDescription = this._navigator.stateService.currentNode$
24231 .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
24232 if (conf.playing !== undefined && !conf.playing) {
24235 var description = null;
24236 for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
24237 var nodeInstruction = _a[_i];
24238 if (nodeInstruction.key === node.key) {
24239 description = nodeInstruction.description;
24243 return description;
24244 }).scan(function (descriptionState, description) {
24245 if (description !== descriptionState.description && description !== null) {
24246 descriptionState.description = description;
24247 descriptionState.showsLeft = 6;
24250 descriptionState.showsLeft--;
24252 if (description === "quit") {
24253 descriptionState.description = null;
24255 return descriptionState;
24256 }, new DescriptionState()).map(function (descriptionState) {
24257 if (descriptionState.showsLeft > 0 && descriptionState.description) {
24258 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
24261 return { name: _this._name, vnode: vd.h("div", []) };
24263 }).subscribe(this._container.domRenderer.render$);
24265 RouteComponent.prototype._deactivate = function () {
24266 this._disposable.unsubscribe();
24267 this._disposableDescription.unsubscribe();
24269 RouteComponent.prototype._getDefaultConfiguration = function () {
24272 RouteComponent.prototype.play = function () {
24273 this.configure({ playing: true });
24275 RouteComponent.prototype.stop = function () {
24276 this.configure({ playing: false });
24278 RouteComponent.prototype._getRouteAnnotationNode = function (description) {
24279 return vd.h("div.RouteFrame", {}, [
24280 vd.h("p", { textContent: description }, []),
24283 RouteComponent.componentName = "route";
24284 return RouteComponent;
24285 }(Component_1.Component));
24286 exports.RouteComponent = RouteComponent;
24287 Component_1.ComponentService.register(RouteComponent);
24288 exports.default = RouteComponent;
24290 },{"../Component":281,"rxjs/Observable":29,"rxjs/add/observable/fromPromise":43,"rxjs/add/observable/of":45,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinct":57,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/pluck":70,"rxjs/add/operator/scan":75,"underscore":233,"virtual-dom":237}],307:[function(require,module,exports){
24292 var __extends = (this && this.__extends) || (function () {
24293 var extendStatics = Object.setPrototypeOf ||
24294 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24295 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24296 return function (d, b) {
24297 extendStatics(d, b);
24298 function __() { this.constructor = d; }
24299 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24302 Object.defineProperty(exports, "__esModule", { value: true });
24303 var Observable_1 = require("rxjs/Observable");
24304 require("rxjs/add/operator/buffer");
24305 require("rxjs/add/operator/debounceTime");
24306 require("rxjs/add/operator/filter");
24307 require("rxjs/add/operator/map");
24308 require("rxjs/add/operator/scan");
24309 var Component_1 = require("../Component");
24310 var StatsComponent = /** @class */ (function (_super) {
24311 __extends(StatsComponent, _super);
24312 function StatsComponent(name, container, navigator) {
24313 return _super.call(this, name, container, navigator) || this;
24315 StatsComponent.prototype._activate = function () {
24317 this._sequenceSubscription = this._navigator.stateService.currentNode$
24318 .scan(function (keys, node) {
24319 var sKey = node.sequenceKey;
24321 if (!(sKey in keys.reported)) {
24322 keys.report = [sKey];
24323 keys.reported[sKey] = true;
24326 }, { report: [], reported: {} })
24327 .filter(function (keys) {
24328 return keys.report.length > 0;
24330 .mergeMap(function (keys) {
24331 return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
24332 .catch(function (error, caught) {
24333 console.error("Failed to report sequence stats (" + keys.report + ")", error);
24334 return Observable_1.Observable.empty();
24337 .subscribe(function () { });
24338 this._imageSubscription = this._navigator.stateService.currentNode$
24339 .map(function (node) {
24342 .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
24343 .scan(function (keys, newKeys) {
24345 for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
24346 var key = newKeys_1[_i];
24347 if (!(key in keys.reported)) {
24348 keys.report.push(key);
24349 keys.reported[key] = true;
24353 }, { report: [], reported: {} })
24354 .filter(function (keys) {
24355 return keys.report.length > 0;
24357 .mergeMap(function (keys) {
24358 return _this._navigator.apiV3.imageViewAdd$(keys.report)
24359 .catch(function (error, caught) {
24360 console.error("Failed to report image stats (" + keys.report + ")", error);
24361 return Observable_1.Observable.empty();
24364 .subscribe(function () { });
24366 StatsComponent.prototype._deactivate = function () {
24367 this._sequenceSubscription.unsubscribe();
24368 this._imageSubscription.unsubscribe();
24370 StatsComponent.prototype._getDefaultConfiguration = function () {
24373 StatsComponent.componentName = "stats";
24374 return StatsComponent;
24375 }(Component_1.Component));
24376 exports.StatsComponent = StatsComponent;
24377 Component_1.ComponentService.register(StatsComponent);
24378 exports.default = StatsComponent;
24380 },{"../Component":281,"rxjs/Observable":29,"rxjs/add/operator/buffer":49,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":75}],308:[function(require,module,exports){
24382 /// <reference path="../../../typings/index.d.ts" />
24383 var __extends = (this && this.__extends) || (function () {
24384 var extendStatics = Object.setPrototypeOf ||
24385 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24386 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24387 return function (d, b) {
24388 extendStatics(d, b);
24389 function __() { this.constructor = d; }
24390 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24393 Object.defineProperty(exports, "__esModule", { value: true });
24394 var vd = require("virtual-dom");
24395 var Observable_1 = require("rxjs/Observable");
24396 var Subject_1 = require("rxjs/Subject");
24397 require("rxjs/add/observable/combineLatest");
24398 require("rxjs/add/operator/do");
24399 require("rxjs/add/operator/distinctUntilChanged");
24400 require("rxjs/add/operator/filter");
24401 require("rxjs/add/operator/map");
24402 require("rxjs/add/operator/share");
24403 var Component_1 = require("../../Component");
24405 * @class DirectionComponent
24406 * @classdesc Component showing navigation arrows for steps and turns.
24408 var DirectionComponent = /** @class */ (function (_super) {
24409 __extends(DirectionComponent, _super);
24410 function DirectionComponent(name, container, navigator, directionDOMRenderer) {
24411 var _this = _super.call(this, name, container, navigator) || this;
24412 _this._renderer = !!directionDOMRenderer ?
24413 directionDOMRenderer :
24414 new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
24415 _this._hoveredKeySubject$ = new Subject_1.Subject();
24416 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
24419 Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
24421 * Get hovered key observable.
24423 * @description An observable emitting the key of the node for the direction
24424 * arrow that is being hovered. When the mouse leaves a direction arrow null
24427 * @returns {Observable<string>}
24430 return this._hoveredKey$;
24436 * Set highlight key.
24438 * @description The arrow pointing towards the node corresponding to the
24439 * highlight key will be highlighted.
24441 * @param {string} highlightKey Key of node to be highlighted if existing
24444 DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
24445 this.configure({ highlightKey: highlightKey });
24448 * Set min width of container element.
24450 * @description Set min width of the non transformed container element holding
24451 * the navigation arrows. If the min width is larger than the max width the
24452 * min width value will be used.
24454 * The container element is automatically resized when the resize
24455 * method on the Viewer class is called.
24457 * @param {number} minWidth
24459 DirectionComponent.prototype.setMinWidth = function (minWidth) {
24460 this.configure({ minWidth: minWidth });
24463 * Set max width of container element.
24465 * @description Set max width of the non transformed container element holding
24466 * the navigation arrows. If the min width is larger than the max width the
24467 * min width value will be used.
24469 * The container element is automatically resized when the resize
24470 * method on the Viewer class is called.
24472 * @param {number} minWidth
24474 DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
24475 this.configure({ maxWidth: maxWidth });
24478 DirectionComponent.prototype.resize = function () {
24479 this._renderer.resize(this._container.element);
24481 DirectionComponent.prototype._activate = function () {
24483 this._configurationSubscription = this._configuration$
24484 .subscribe(function (configuration) {
24485 _this._renderer.setConfiguration(configuration);
24487 this._nodeSubscription = this._navigator.stateService.currentNode$
24488 .do(function (node) {
24489 _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
24490 _this._renderer.setNode(node);
24492 .withLatestFrom(this._configuration$)
24493 .switchMap(function (_a) {
24494 var node = _a[0], configuration = _a[1];
24495 return Observable_1.Observable
24496 .combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
24497 _this._navigator.graphService
24498 .cacheSequence$(node.sequenceKey)
24499 .catch(function (error, caught) {
24500 console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
24501 return Observable_1.Observable.of(null);
24503 Observable_1.Observable.of(null));
24505 .subscribe(function (_a) {
24506 var edgeStatus = _a[0], sequence = _a[1];
24507 _this._renderer.setEdges(edgeStatus, sequence);
24509 this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
24510 .do(function (renderCamera) {
24511 _this._renderer.setRenderCamera(renderCamera);
24513 .map(function (renderCamera) {
24514 return _this._renderer;
24516 .filter(function (renderer) {
24517 return renderer.needsRender;
24519 .map(function (renderer) {
24520 return { name: _this._name, vnode: renderer.render(_this._navigator) };
24522 .subscribe(this._container.domRenderer.render$);
24523 this._hoveredKeySubscription = Observable_1.Observable
24525 this._container.domRenderer.element$,
24526 this._container.renderService.renderCamera$,
24527 this._container.mouseService.mouseMove$.startWith(null),
24528 this._container.mouseService.mouseUp$.startWith(null),
24529 ], function (e, rc, mm, mu) {
24532 .map(function (element) {
24533 var elements = element.getElementsByClassName("DirectionsPerspective");
24534 for (var i = 0; i < elements.length; i++) {
24535 var hovered = elements.item(i).querySelector(":hover");
24536 if (hovered != null && hovered.hasAttribute("data-key")) {
24537 return hovered.getAttribute("data-key");
24542 .distinctUntilChanged()
24543 .subscribe(this._hoveredKeySubject$);
24545 DirectionComponent.prototype._deactivate = function () {
24546 this._configurationSubscription.unsubscribe();
24547 this._nodeSubscription.unsubscribe();
24548 this._renderCameraSubscription.unsubscribe();
24549 this._hoveredKeySubscription.unsubscribe();
24551 DirectionComponent.prototype._getDefaultConfiguration = function () {
24553 distinguishSequence: false,
24559 DirectionComponent.componentName = "direction";
24560 return DirectionComponent;
24561 }(Component_1.Component));
24562 exports.DirectionComponent = DirectionComponent;
24563 Component_1.ComponentService.register(DirectionComponent);
24564 exports.default = DirectionComponent;
24566 },{"../../Component":281,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/share":76,"virtual-dom":237}],309:[function(require,module,exports){
24568 Object.defineProperty(exports, "__esModule", { value: true });
24569 var Geo_1 = require("../../Geo");
24571 * @class DirectionDOMCalculator
24572 * @classdesc Helper class for calculating DOM CSS properties.
24574 var DirectionDOMCalculator = /** @class */ (function () {
24575 function DirectionDOMCalculator(configuration, element) {
24576 this._spatial = new Geo_1.Spatial();
24577 this._minThresholdWidth = 320;
24578 this._maxThresholdWidth = 1480;
24579 this._minThresholdHeight = 240;
24580 this._maxThresholdHeight = 820;
24581 this._configure(configuration);
24582 this._resize(element);
24585 Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
24587 return this._minWidth;
24592 Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
24594 return this._maxWidth;
24599 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
24601 return this._containerWidth;
24606 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
24608 return this._containerWidthCss;
24613 Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
24615 return this._containerMarginCss;
24620 Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
24622 return this._containerLeftCss;
24627 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
24629 return this._containerHeight;
24634 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
24636 return this._containerHeightCss;
24641 Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
24643 return this._containerBottomCss;
24648 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
24650 return this._stepCircleSize;
24655 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
24657 return this._stepCircleSizeCss;
24662 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
24664 return this._stepCircleMarginCss;
24669 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
24671 return this._turnCircleSize;
24676 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
24678 return this._turnCircleSizeCss;
24683 Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
24685 return this._outerRadius;
24690 Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
24692 return this._innerRadius;
24697 Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
24699 return this._shadowOffset;
24705 * Configures the min and max width values.
24707 * @param {IDirectionConfiguration} configuration Configuration
24708 * with min and max width values.
24710 DirectionDOMCalculator.prototype.configure = function (configuration) {
24711 this._configure(configuration);
24715 * Resizes all properties according to the width and height
24718 * @param {HTMLElement} element The container element from which to extract
24719 * the width and height.
24721 DirectionDOMCalculator.prototype.resize = function (element) {
24722 this._resize(element);
24726 * Calculates the coordinates on the unit circle for an angle.
24728 * @param {number} angle Angle in radians.
24729 * @returns {Array<number>} The x and y coordinates on the unit circle.
24731 DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
24732 return [Math.cos(angle), Math.sin(angle)];
24735 * Calculates the coordinates on the unit circle for the
24736 * relative angle between the first and second angle.
24738 * @param {number} first Angle in radians.
24739 * @param {number} second Angle in radians.
24740 * @returns {Array<number>} The x and y coordinates on the unit circle
24741 * for the relative angle between the first and second angle.
24743 DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
24744 var relativeAngle = this._spatial.wrapAngle(first - second);
24745 return this.angleToCoordinates(relativeAngle);
24747 DirectionDOMCalculator.prototype._configure = function (configuration) {
24748 this._minWidth = configuration.minWidth;
24749 this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
24751 DirectionDOMCalculator.prototype._resize = function (element) {
24752 this._elementWidth = element.offsetWidth;
24753 this._elementHeight = element.offsetHeight;
24755 DirectionDOMCalculator.prototype._reset = function () {
24756 this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
24757 this._containerHeight = this._getContainerHeight(this.containerWidth);
24758 this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
24759 this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
24760 this._outerRadius = this._getOuterRadius(this._containerHeight);
24761 this._innerRadius = this._getInnerRadius(this._containerHeight);
24762 this._shadowOffset = 3;
24763 this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
24764 this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
24765 this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
24766 this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
24767 this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
24768 this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
24769 this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
24770 this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
24772 DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
24773 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
24774 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
24775 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
24776 coeff = 0.04 * Math.round(25 * coeff);
24777 return this._minWidth + coeff * (this._maxWidth - this._minWidth);
24779 DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
24780 return 0.77 * containerWidth;
24782 DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
24783 return 0.34 * containerHeight;
24785 DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
24786 return 0.3 * containerHeight;
24788 DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
24789 return 0.31 * containerHeight;
24791 DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
24792 return 0.125 * containerHeight;
24794 DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
24795 return value + "px";
24797 DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
24798 return value > minWidth ? value : minWidth;
24800 return DirectionDOMCalculator;
24802 exports.DirectionDOMCalculator = DirectionDOMCalculator;
24803 exports.default = DirectionDOMCalculator;
24805 },{"../../Geo":284}],310:[function(require,module,exports){
24807 /// <reference path="../../../typings/index.d.ts" />
24808 Object.defineProperty(exports, "__esModule", { value: true });
24809 var vd = require("virtual-dom");
24810 var Component_1 = require("../../Component");
24811 var Edge_1 = require("../../Edge");
24812 var Geo_1 = require("../../Geo");
24814 * @class DirectionDOMRenderer
24815 * @classdesc DOM renderer for direction arrows.
24817 var DirectionDOMRenderer = /** @class */ (function () {
24818 function DirectionDOMRenderer(configuration, element) {
24819 this._isEdge = false;
24820 this._spatial = new Geo_1.Spatial();
24821 this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
24823 this._rotation = { phi: 0, theta: 0 };
24824 this._epsilon = 0.5 * Math.PI / 180;
24825 this._highlightKey = null;
24826 this._distinguishSequence = false;
24827 this._needsRender = false;
24828 this._stepEdges = [];
24829 this._turnEdges = [];
24830 this._panoEdges = [];
24831 this._sequenceEdgeKeys = [];
24832 this._stepDirections = [
24833 Edge_1.EdgeDirection.StepForward,
24834 Edge_1.EdgeDirection.StepBackward,
24835 Edge_1.EdgeDirection.StepLeft,
24836 Edge_1.EdgeDirection.StepRight,
24838 this._turnDirections = [
24839 Edge_1.EdgeDirection.TurnLeft,
24840 Edge_1.EdgeDirection.TurnRight,
24841 Edge_1.EdgeDirection.TurnU,
24843 this._turnNames = {};
24844 this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
24845 this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
24846 this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
24847 // detects IE 8-11, then Edge 20+.
24848 var isIE = !!document.documentMode;
24849 this._isEdge = !isIE && !!window.StyleMedia;
24851 Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
24853 * Get needs render.
24855 * @returns {boolean} Value indicating whether render should be called.
24858 return this._needsRender;
24864 * Renders virtual DOM elements.
24866 * @description Calling render resets the needs render property.
24868 DirectionDOMRenderer.prototype.render = function (navigator) {
24869 this._needsRender = false;
24870 var rotation = this._rotation;
24873 if (this._node.pano) {
24874 steps = steps.concat(this._createPanoArrows(navigator, rotation));
24877 steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
24878 steps = steps.concat(this._createStepArrows(navigator, rotation));
24879 turns = turns.concat(this._createTurnArrows(navigator));
24881 return this._getContainer(steps, turns, rotation);
24883 DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
24884 this._setEdges(edgeStatus, sequence);
24885 this._setNeedsRender();
24888 * Set node for which to show edges.
24890 * @param {Node} node
24892 DirectionDOMRenderer.prototype.setNode = function (node) {
24894 this._clearEdges();
24895 this._setNeedsRender();
24898 * Set the render camera to use for calculating rotations.
24900 * @param {RenderCamera} renderCamera
24902 DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
24903 var rotation = renderCamera.rotation;
24904 if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
24907 this._rotation = rotation;
24908 this._setNeedsRender();
24911 * Set configuration values.
24913 * @param {IDirectionConfiguration} configuration
24915 DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
24916 var needsRender = false;
24917 if (this._highlightKey !== configuration.highlightKey ||
24918 this._distinguishSequence !== configuration.distinguishSequence) {
24919 this._highlightKey = configuration.highlightKey;
24920 this._distinguishSequence = configuration.distinguishSequence;
24921 needsRender = true;
24923 if (this._calculator.minWidth !== configuration.minWidth ||
24924 this._calculator.maxWidth !== configuration.maxWidth) {
24925 this._calculator.configure(configuration);
24926 needsRender = true;
24929 this._setNeedsRender();
24933 * Detect the element's width and height and resize
24934 * elements accordingly.
24936 * @param {HTMLElement} element Viewer container element.
24938 DirectionDOMRenderer.prototype.resize = function (element) {
24939 this._calculator.resize(element);
24940 this._setNeedsRender();
24942 DirectionDOMRenderer.prototype._setNeedsRender = function () {
24943 if (this._node != null) {
24944 this._needsRender = true;
24947 DirectionDOMRenderer.prototype._clearEdges = function () {
24948 this._stepEdges = [];
24949 this._turnEdges = [];
24950 this._panoEdges = [];
24951 this._sequenceEdgeKeys = [];
24953 DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
24954 this._stepEdges = [];
24955 this._turnEdges = [];
24956 this._panoEdges = [];
24957 this._sequenceEdgeKeys = [];
24958 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
24960 var direction = edge.data.direction;
24961 if (this._stepDirections.indexOf(direction) > -1) {
24962 this._stepEdges.push(edge);
24965 if (this._turnDirections.indexOf(direction) > -1) {
24966 this._turnEdges.push(edge);
24969 if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
24970 this._panoEdges.push(edge);
24973 if (this._distinguishSequence && sequence != null) {
24974 var edges = this._panoEdges
24975 .concat(this._stepEdges)
24976 .concat(this._turnEdges);
24977 for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
24978 var edge = edges_1[_b];
24979 var edgeKey = edge.to;
24980 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
24981 var sequenceKey = _d[_c];
24982 if (sequenceKey === edgeKey) {
24983 this._sequenceEdgeKeys.push(edgeKey);
24990 DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
24992 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
24993 var panoEdge = _a[_i];
24994 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
24996 for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
24997 var stepEdge = _c[_b];
24998 arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25002 DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
25003 var threshold = Math.PI / 8;
25004 var relativePhi = rotation.phi;
25005 switch (direction) {
25006 case Edge_1.EdgeDirection.StepBackward:
25007 relativePhi = rotation.phi - Math.PI;
25009 case Edge_1.EdgeDirection.StepLeft:
25010 relativePhi = rotation.phi + Math.PI / 2;
25012 case Edge_1.EdgeDirection.StepRight:
25013 relativePhi = rotation.phi - Math.PI / 2;
25018 if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
25019 return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
25021 return this._createVNodeDisabled(key, azimuth, rotation);
25023 DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
25025 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
25026 var panoEdge = _a[_i];
25027 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
25031 DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
25033 for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
25034 var stepEdge = _a[_i];
25035 arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25039 DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
25041 for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
25042 var turnEdge = _a[_i];
25043 var direction = turnEdge.data.direction;
25044 var name_1 = this._turnNames[direction];
25045 turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
25049 DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
25050 var onClick = function (e) {
25051 navigator.moveToKey$(key)
25052 .subscribe(function (node) { return; }, function (error) { console.error(error); });
25054 return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
25056 DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
25057 var onClick = function (e) {
25058 navigator.moveDir$(direction)
25059 .subscribe(function (node) { return; }, function (error) { console.error(error); });
25061 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
25063 DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
25064 var onClick = function (e) {
25065 navigator.moveDir$(direction)
25066 .subscribe(function (node) { return; }, function (error) { console.error(error); });
25069 height: this._calculator.turnCircleSizeCss,
25070 transform: "rotate(0)",
25071 width: this._calculator.turnCircleSizeCss,
25073 switch (direction) {
25074 case Edge_1.EdgeDirection.TurnLeft:
25075 style.left = "5px";
25078 case Edge_1.EdgeDirection.TurnRight:
25079 style.right = "5px";
25082 case Edge_1.EdgeDirection.TurnU:
25083 style.left = "5px";
25084 style.bottom = "5px";
25089 var circleProperties = {
25096 var circleClassName = "TurnCircle";
25097 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25098 circleClassName += "Sequence";
25100 if (this._highlightKey === key) {
25101 circleClassName += "Highlight";
25103 var turn = vd.h("div." + className, {}, []);
25104 return vd.h("div." + circleClassName, circleProperties, [turn]);
25106 DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
25107 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
25109 DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
25110 var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
25111 // rotate 90 degrees clockwise and flip over X-axis
25112 var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
25113 var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
25114 var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
25115 var shadowOffset = this._calculator.shadowOffset;
25116 var shadowTranslationX = -shadowOffset * shadowTranslation[1];
25117 var shadowTranslationY = shadowOffset * shadowTranslation[0];
25118 var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
25121 "-webkit-filter": filter,
25125 var chevron = vd.h("div." + className, properties, []);
25126 var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
25127 var circleTransform = shiftVertically ?
25128 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
25129 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
25130 var circleProperties = {
25131 attributes: { "data-key": key },
25134 height: this._calculator.stepCircleSizeCss,
25135 marginLeft: this._calculator.stepCircleMarginCss,
25136 marginTop: this._calculator.stepCircleMarginCss,
25137 transform: circleTransform,
25138 width: this._calculator.stepCircleSizeCss,
25141 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25142 circleClassName += "Sequence";
25144 if (this._highlightKey === key) {
25145 circleClassName += "Highlight";
25147 return vd.h("div." + circleClassName, circleProperties, [chevron]);
25149 DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
25150 // edge does not handle hover on perspective transforms.
25151 var transform = this._isEdge ?
25153 "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
25155 oncontextmenu: function (event) { event.preventDefault(); },
25157 bottom: this._calculator.containerBottomCss,
25158 height: this._calculator.containerHeightCss,
25159 left: this._calculator.containerLeftCss,
25160 marginLeft: this._calculator.containerMarginCss,
25161 transform: transform,
25162 width: this._calculator.containerWidthCss,
25165 return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
25167 return DirectionDOMRenderer;
25169 exports.DirectionDOMRenderer = DirectionDOMRenderer;
25170 exports.default = DirectionDOMRenderer;
25172 },{"../../Component":281,"../../Edge":282,"../../Geo":284,"virtual-dom":237}],311:[function(require,module,exports){
25174 var __extends = (this && this.__extends) || (function () {
25175 var extendStatics = Object.setPrototypeOf ||
25176 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25177 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25178 return function (d, b) {
25179 extendStatics(d, b);
25180 function __() { this.constructor = d; }
25181 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25184 Object.defineProperty(exports, "__esModule", { value: true });
25185 var Observable_1 = require("rxjs/Observable");
25186 var Subject_1 = require("rxjs/Subject");
25187 require("rxjs/add/operator/catch");
25188 require("rxjs/add/operator/combineLatest");
25189 require("rxjs/add/operator/debounceTime");
25190 require("rxjs/add/operator/distinctUntilChanged");
25191 require("rxjs/add/operator/filter");
25192 require("rxjs/add/operator/map");
25193 require("rxjs/add/operator/pairwise");
25194 require("rxjs/add/operator/publish");
25195 require("rxjs/add/operator/publishReplay");
25196 require("rxjs/add/operator/scan");
25197 require("rxjs/add/operator/skipWhile");
25198 require("rxjs/add/operator/startWith");
25199 require("rxjs/add/operator/switchMap");
25200 require("rxjs/add/operator/takeUntil");
25201 require("rxjs/add/operator/withLatestFrom");
25202 var Component_1 = require("../../Component");
25203 var Render_1 = require("../../Render");
25204 var Tiles_1 = require("../../Tiles");
25205 var Utils_1 = require("../../Utils");
25206 var ImagePlaneComponent = /** @class */ (function (_super) {
25207 __extends(ImagePlaneComponent, _super);
25208 function ImagePlaneComponent(name, container, navigator) {
25209 var _this = _super.call(this, name, container, navigator) || this;
25210 _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
25211 _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
25212 _this._rendererOperation$ = new Subject_1.Subject();
25213 _this._rendererCreator$ = new Subject_1.Subject();
25214 _this._rendererDisposer$ = new Subject_1.Subject();
25215 _this._renderer$ = _this._rendererOperation$
25216 .scan(function (renderer, operation) {
25217 return operation(renderer);
25219 .filter(function (renderer) {
25220 return renderer != null;
25222 .distinctUntilChanged(undefined, function (renderer) {
25223 return renderer.frameId;
25225 _this._rendererCreator$
25227 return function (renderer) {
25228 if (renderer != null) {
25229 throw new Error("Multiple image plane states can not be created at the same time");
25231 return new Component_1.ImagePlaneGLRenderer();
25234 .subscribe(_this._rendererOperation$);
25235 _this._rendererDisposer$
25237 return function (renderer) {
25238 renderer.dispose();
25242 .subscribe(_this._rendererOperation$);
25245 ImagePlaneComponent.prototype._activate = function () {
25247 this._rendererSubscription = this._renderer$
25248 .map(function (renderer) {
25252 frameId: renderer.frameId,
25253 needsRender: renderer.needsRender,
25254 render: renderer.render.bind(renderer),
25255 stage: Render_1.GLRenderStage.Background,
25258 renderer.clearNeedsRender();
25261 .subscribe(this._container.glRenderer.render$);
25262 this._rendererCreator$.next(null);
25263 this._stateSubscription = this._navigator.stateService.currentState$
25264 .map(function (frame) {
25265 return function (renderer) {
25266 renderer.updateFrame(frame);
25270 .subscribe(this._rendererOperation$);
25271 var textureProvider$ = this._navigator.stateService.currentState$
25272 .distinctUntilChanged(undefined, function (frame) {
25273 return frame.state.currentNode.key;
25275 .combineLatest(this._configuration$)
25276 .filter(function (args) {
25277 return args[1].imageTiling === true;
25279 .map(function (args) {
25282 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
25283 .map(function (_a) {
25284 var frame = _a[0], renderer = _a[1], size = _a[2];
25285 var state = frame.state;
25286 var viewportSize = Math.max(size.width, size.height);
25287 var currentNode = state.currentNode;
25288 var currentTransform = state.currentTransform;
25289 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25290 return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
25294 this._textureProviderSubscription = textureProvider$.subscribe(function () { });
25295 this._setTextureProviderSubscription = textureProvider$
25296 .map(function (provider) {
25297 return function (renderer) {
25298 renderer.setTextureProvider(provider.key, provider);
25302 .subscribe(this._rendererOperation$);
25303 this._setTileSizeSubscription = this._container.renderService.size$
25304 .switchMap(function (size) {
25305 return Observable_1.Observable
25306 .combineLatest(textureProvider$, Observable_1.Observable.of(size))
25309 .subscribe(function (_a) {
25310 var provider = _a[0], size = _a[1];
25311 var viewportSize = Math.max(size.width, size.height);
25312 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25313 provider.setTileSize(tileSize);
25315 this._abortTextureProviderSubscription = textureProvider$
25317 .subscribe(function (pair) {
25318 var previous = pair[0];
25321 var roiTrigger$ = Observable_1.Observable
25322 .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250))
25323 .map(function (_a) {
25324 var camera = _a[0], size = _a[1];
25326 camera.camera.position.clone(),
25327 camera.camera.lookat.clone(),
25328 camera.zoom.valueOf(),
25329 size.height.valueOf(),
25330 size.width.valueOf()
25334 .skipWhile(function (pls) {
25335 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
25337 .map(function (pls) {
25338 var samePosition = pls[0][0].equals(pls[1][0]);
25339 var sameLookat = pls[0][1].equals(pls[1][1]);
25340 var sameZoom = pls[0][2] === pls[1][2];
25341 var sameHeight = pls[0][3] === pls[1][3];
25342 var sameWidth = pls[0][4] === pls[1][4];
25343 return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
25345 .distinctUntilChanged()
25346 .filter(function (stalled) {
25349 .switchMap(function (stalled) {
25350 return _this._container.renderService.renderCameraFrame$
25353 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
25354 this._setRegionOfInterestSubscription = textureProvider$
25355 .switchMap(function (provider) {
25357 .map(function (_a) {
25358 var camera = _a[0], size = _a[1], transform = _a[2];
25360 _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
25365 .filter(function (args) {
25366 return !args[1].disposed;
25368 .subscribe(function (args) {
25370 var provider = args[1];
25371 provider.setRegionOfInterest(roi);
25373 var hasTexture$ = textureProvider$
25374 .switchMap(function (provider) {
25375 return provider.hasTexture$;
25380 this._hasTextureSubscription = hasTexture$.subscribe(function () { });
25381 var nodeImage$ = this._navigator.stateService.currentState$
25382 .filter(function (frame) {
25383 return frame.state.nodesAhead === 0;
25385 .map(function (frame) {
25386 return frame.state.currentNode;
25388 .distinctUntilChanged(undefined, function (node) {
25391 .debounceTime(1000)
25392 .withLatestFrom(hasTexture$)
25393 .filter(function (args) {
25396 .map(function (args) {
25399 .filter(function (node) {
25401 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
25402 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
25404 .switchMap(function (node) {
25405 var baseImageSize = node.pano ?
25406 Utils_1.Settings.basePanoramaSize :
25407 Utils_1.Settings.baseImageSize;
25408 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
25409 return Observable_1.Observable.empty();
25412 .cacheImage$(Utils_1.Settings.maxImageSize)
25413 .map(function (n) {
25414 return [n.image, n];
25417 .takeUntil(hasTexture$
25418 .filter(function (hasTexture) {
25421 .catch(function (error, caught) {
25422 console.error("Failed to fetch high res image (" + node.key + ")", error);
25423 return Observable_1.Observable.empty();
25428 this._updateBackgroundSubscription = nodeImage$
25429 .withLatestFrom(textureProvider$)
25430 .subscribe(function (args) {
25431 if (args[0][1].key !== args[1].key ||
25432 args[1].disposed) {
25435 args[1].updateBackground(args[0][0]);
25437 this._updateTextureImageSubscription = nodeImage$
25438 .map(function (imn) {
25439 return function (renderer) {
25440 renderer.updateTextureImage(imn[0], imn[1]);
25444 .subscribe(this._rendererOperation$);
25446 ImagePlaneComponent.prototype._deactivate = function () {
25447 this._rendererDisposer$.next(null);
25448 this._abortTextureProviderSubscription.unsubscribe();
25449 this._hasTextureSubscription.unsubscribe();
25450 this._rendererSubscription.unsubscribe();
25451 this._setRegionOfInterestSubscription.unsubscribe();
25452 this._setTextureProviderSubscription.unsubscribe();
25453 this._setTileSizeSubscription.unsubscribe();
25454 this._stateSubscription.unsubscribe();
25455 this._textureProviderSubscription.unsubscribe();
25456 this._updateBackgroundSubscription.unsubscribe();
25457 this._updateTextureImageSubscription.unsubscribe();
25459 ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
25460 return { imageTiling: false };
25462 ImagePlaneComponent.componentName = "imagePlane";
25463 return ImagePlaneComponent;
25464 }(Component_1.Component));
25465 exports.ImagePlaneComponent = ImagePlaneComponent;
25466 Component_1.ComponentService.register(ImagePlaneComponent);
25467 exports.default = ImagePlaneComponent;
25469 },{"../../Component":281,"../../Render":287,"../../Tiles":290,"../../Utils":291,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":52,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/pairwise":69,"rxjs/add/operator/publish":71,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/skipWhile":79,"rxjs/add/operator/startWith":80,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/takeUntil":83,"rxjs/add/operator/withLatestFrom":87}],312:[function(require,module,exports){
25471 /// <reference path="../../../typings/index.d.ts" />
25472 Object.defineProperty(exports, "__esModule", { value: true });
25473 var THREE = require("three");
25474 var Component_1 = require("../../Component");
25475 var ImagePlaneFactory = /** @class */ (function () {
25476 function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
25477 this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
25478 this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
25480 ImagePlaneFactory.prototype.createMesh = function (node, transform) {
25481 var mesh = node.pano ?
25482 this._createImageSphere(node, transform) :
25483 this._createImagePlane(node, transform);
25486 ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
25487 var texture = this._createTexture(node.image);
25488 var materialParameters = this._createSphereMaterialParameters(transform, texture);
25489 var material = new THREE.ShaderMaterial(materialParameters);
25490 var mesh = this._useMesh(transform, node) ?
25491 new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
25492 new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
25495 ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
25496 var texture = this._createTexture(node.image);
25497 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
25498 var material = new THREE.ShaderMaterial(materialParameters);
25499 var geometry = this._useMesh(transform, node) ?
25500 this._getImagePlaneGeo(transform, node) :
25501 this._getFlatImagePlaneGeo(transform);
25502 return new THREE.Mesh(geometry, material);
25504 ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
25505 var gpano = transform.gpano;
25506 var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
25507 var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
25508 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
25509 var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
25510 var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
25511 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
25512 var materialParameters = {
25514 fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
25515 side: THREE.DoubleSide,
25532 value: transform.rt,
25540 value: thetaLength,
25547 vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
25549 return materialParameters;
25551 ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
25552 var materialParameters = {
25554 fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
25555 side: THREE.DoubleSide,
25560 value: new THREE.Vector4(0, 0, 1, 1),
25568 value: transform.projectorMatrix(),
25575 vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
25577 return materialParameters;
25579 ImagePlaneFactory.prototype._createTexture = function (image) {
25580 var texture = new THREE.Texture(image);
25581 texture.minFilter = THREE.LinearFilter;
25582 texture.needsUpdate = true;
25585 ImagePlaneFactory.prototype._useMesh = function (transform, node) {
25586 return node.mesh.vertices.length && transform.hasValidScale;
25588 ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
25589 var t = new THREE.Matrix4().getInverse(transform.srt);
25590 // push everything at least 5 meters in front of the camera
25591 var minZ = 5.0 * transform.scale;
25592 var maxZ = this._imageSphereRadius * transform.scale;
25593 var vertices = node.mesh.vertices;
25594 var numVertices = vertices.length / 3;
25595 var positions = new Float32Array(vertices.length);
25596 for (var i = 0; i < numVertices; ++i) {
25598 var x = vertices[index + 0];
25599 var y = vertices[index + 1];
25600 var z = vertices[index + 2];
25601 var l = Math.sqrt(x * x + y * y + z * z);
25602 var boundedL = Math.max(minZ, Math.min(l, maxZ));
25603 var factor = boundedL / l;
25604 var p = new THREE.Vector3(x * factor, y * factor, z * factor);
25606 positions[index + 0] = p.x;
25607 positions[index + 1] = p.y;
25608 positions[index + 2] = p.z;
25610 var faces = node.mesh.faces;
25611 var indices = new Uint16Array(faces.length);
25612 for (var i = 0; i < faces.length; ++i) {
25613 indices[i] = faces[i];
25615 var geometry = new THREE.BufferGeometry();
25616 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
25617 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
25620 ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
25621 var t = new THREE.Matrix4().getInverse(transform.srt);
25622 // push everything at least 5 meters in front of the camera
25623 var minZ = 5.0 * transform.scale;
25624 var maxZ = this._imagePlaneDepth * transform.scale;
25625 var vertices = node.mesh.vertices;
25626 var numVertices = vertices.length / 3;
25627 var positions = new Float32Array(vertices.length);
25628 for (var i = 0; i < numVertices; ++i) {
25630 var x = vertices[index + 0];
25631 var y = vertices[index + 1];
25632 var z = vertices[index + 2];
25633 var boundedZ = Math.max(minZ, Math.min(z, maxZ));
25634 var factor = boundedZ / z;
25635 var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
25637 positions[index + 0] = p.x;
25638 positions[index + 1] = p.y;
25639 positions[index + 2] = p.z;
25641 var faces = node.mesh.faces;
25642 var indices = new Uint16Array(faces.length);
25643 for (var i = 0; i < faces.length; ++i) {
25644 indices[i] = faces[i];
25646 var geometry = new THREE.BufferGeometry();
25647 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
25648 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
25651 ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
25652 var gpano = transform.gpano;
25653 var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
25654 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
25655 var thetaStart = Math.PI *
25656 (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
25657 gpano.FullPanoHeightPixels;
25658 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
25659 var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
25660 geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
25663 ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
25664 var width = transform.width;
25665 var height = transform.height;
25666 var size = Math.max(width, height);
25667 var dx = width / 2.0 / size;
25668 var dy = height / 2.0 / size;
25670 vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
25671 vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
25672 vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
25673 vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
25674 var positions = new Float32Array(12);
25675 for (var i = 0; i < vertices.length; i++) {
25677 positions[index + 0] = vertices[i][0];
25678 positions[index + 1] = vertices[i][1];
25679 positions[index + 2] = vertices[i][2];
25681 var indices = new Uint16Array(6);
25688 var geometry = new THREE.BufferGeometry();
25689 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
25690 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
25693 return ImagePlaneFactory;
25695 exports.ImagePlaneFactory = ImagePlaneFactory;
25696 exports.default = ImagePlaneFactory;
25698 },{"../../Component":281,"three":231}],313:[function(require,module,exports){
25700 /// <reference path="../../../typings/index.d.ts" />
25701 Object.defineProperty(exports, "__esModule", { value: true });
25702 var Component_1 = require("../../Component");
25703 var ImagePlaneGLRenderer = /** @class */ (function () {
25704 function ImagePlaneGLRenderer() {
25705 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
25706 this._imagePlaneScene = new Component_1.ImagePlaneScene();
25708 this._alphaOld = 0;
25709 this._fadeOutSpeed = 0.05;
25710 this._currentKey = null;
25711 this._previousKey = null;
25712 this._providerDisposers = {};
25714 this._needsRender = false;
25716 Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
25718 return this._frameId;
25723 Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
25725 return this._needsRender;
25730 ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
25731 this._needsRender = true;
25733 ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
25734 this._updateFrameId(frame.id);
25735 this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
25736 this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
25737 this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
25739 ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
25741 if (key !== this._currentKey) {
25744 var createdSubscription = provider.textureCreated$
25745 .subscribe(function (texture) {
25746 _this._updateTexture(texture);
25748 var updatedSubscription = provider.textureUpdated$
25749 .subscribe(function (updated) {
25750 _this._needsRender = true;
25752 var dispose = function () {
25753 createdSubscription.unsubscribe();
25754 updatedSubscription.unsubscribe();
25755 provider.dispose();
25757 if (key in this._providerDisposers) {
25758 var disposeProvider = this._providerDisposers[key];
25760 delete this._providerDisposers[key];
25762 this._providerDisposers[key] = dispose;
25764 ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
25765 this._needsRender = true;
25766 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
25767 var plane = _a[_i];
25768 var material = plane.material;
25769 var oldTexture = material.uniforms.projectorTex.value;
25770 material.uniforms.projectorTex.value = null;
25771 oldTexture.dispose();
25772 material.uniforms.projectorTex.value = texture;
25775 ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
25776 if (this._currentKey !== node.key) {
25779 this._needsRender = true;
25780 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
25781 var plane = _a[_i];
25782 var material = plane.material;
25783 var texture = material.uniforms.projectorTex.value;
25784 texture.image = image;
25785 texture.needsUpdate = true;
25788 ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
25789 var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
25790 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
25791 var plane = _a[_i];
25792 plane.material.uniforms.opacity.value = planeAlpha;
25794 for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
25795 var plane = _c[_b];
25796 plane.material.uniforms.opacity.value = this._alphaOld;
25798 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
25799 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
25800 for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
25801 var plane = _e[_d];
25802 plane.material.uniforms.opacity.value = this._alpha;
25804 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
25806 ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
25807 this._needsRender = false;
25809 ImagePlaneGLRenderer.prototype.dispose = function () {
25810 this._imagePlaneScene.clear();
25812 ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
25813 this._frameId = frameId;
25815 ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
25816 if (alpha === this._alpha) {
25819 this._alpha = alpha;
25822 ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
25823 if (alpha < 1 || this._alphaOld === 0) {
25826 this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
25829 ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
25830 if (state.currentNode == null || state.currentNode.key === this._currentKey) {
25833 var previousKey = state.previousNode != null ? state.previousNode.key : null;
25834 var currentKey = state.currentNode.key;
25835 if (this._previousKey !== previousKey &&
25836 this._previousKey !== currentKey &&
25837 this._previousKey in this._providerDisposers) {
25838 var disposeProvider = this._providerDisposers[this._previousKey];
25840 delete this._providerDisposers[this._previousKey];
25842 if (previousKey != null) {
25843 if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
25844 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
25845 this._imagePlaneScene.updateImagePlanes([previousMesh]);
25847 this._previousKey = previousKey;
25849 this._currentKey = currentKey;
25850 var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
25851 this._imagePlaneScene.updateImagePlanes([currentMesh]);
25852 this._alphaOld = 1;
25855 return ImagePlaneGLRenderer;
25857 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
25858 exports.default = ImagePlaneGLRenderer;
25860 },{"../../Component":281}],314:[function(require,module,exports){
25862 /// <reference path="../../../typings/index.d.ts" />
25863 Object.defineProperty(exports, "__esModule", { value: true });
25864 var THREE = require("three");
25865 var ImagePlaneScene = /** @class */ (function () {
25866 function ImagePlaneScene() {
25867 this.scene = new THREE.Scene();
25868 this.sceneOld = new THREE.Scene();
25869 this.imagePlanes = [];
25870 this.imagePlanesOld = [];
25872 ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
25873 this._dispose(this.imagePlanesOld, this.sceneOld);
25874 for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
25875 var plane = _a[_i];
25876 this.scene.remove(plane);
25877 this.sceneOld.add(plane);
25879 for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
25880 var plane = planes_1[_b];
25881 this.scene.add(plane);
25883 this.imagePlanesOld = this.imagePlanes;
25884 this.imagePlanes = planes;
25886 ImagePlaneScene.prototype.addImagePlanes = function (planes) {
25887 for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
25888 var plane = planes_2[_i];
25889 this.scene.add(plane);
25890 this.imagePlanes.push(plane);
25893 ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
25894 for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
25895 var plane = planes_3[_i];
25896 this.sceneOld.add(plane);
25897 this.imagePlanesOld.push(plane);
25900 ImagePlaneScene.prototype.setImagePlanes = function (planes) {
25902 this.addImagePlanes(planes);
25904 ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
25906 this.addImagePlanesOld(planes);
25908 ImagePlaneScene.prototype.clear = function () {
25912 ImagePlaneScene.prototype._clear = function () {
25913 this._dispose(this.imagePlanes, this.scene);
25914 this.imagePlanes.length = 0;
25916 ImagePlaneScene.prototype._clearOld = function () {
25917 this._dispose(this.imagePlanesOld, this.sceneOld);
25918 this.imagePlanesOld.length = 0;
25920 ImagePlaneScene.prototype._dispose = function (planes, scene) {
25921 for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
25922 var plane = planes_4[_i];
25923 scene.remove(plane);
25924 plane.geometry.dispose();
25925 plane.material.dispose();
25926 var texture = plane.material.uniforms.projectorTex.value;
25927 if (texture != null) {
25932 return ImagePlaneScene;
25934 exports.ImagePlaneScene = ImagePlaneScene;
25935 exports.default = ImagePlaneScene;
25937 },{"three":231}],315:[function(require,module,exports){
25939 /// <reference path="../../../typings/index.d.ts" />
25940 Object.defineProperty(exports, "__esModule", { value: true });
25942 var path = require("path");
25943 var ImagePlaneShaders = /** @class */ (function () {
25944 function ImagePlaneShaders() {
25946 ImagePlaneShaders.equirectangular = {
25947 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}",
25948 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}",
25950 ImagePlaneShaders.perspective = {
25951 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;\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}",
25952 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}",
25954 return ImagePlaneShaders;
25956 exports.ImagePlaneShaders = ImagePlaneShaders;
25958 },{"path":22}],316:[function(require,module,exports){
25960 /// <reference path="../../../typings/index.d.ts" />
25961 var __extends = (this && this.__extends) || (function () {
25962 var extendStatics = Object.setPrototypeOf ||
25963 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25964 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25965 return function (d, b) {
25966 extendStatics(d, b);
25967 function __() { this.constructor = d; }
25968 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25971 Object.defineProperty(exports, "__esModule", { value: true });
25972 var Observable_1 = require("rxjs/Observable");
25973 var Subject_1 = require("rxjs/Subject");
25974 require("rxjs/add/observable/combineLatest");
25975 require("rxjs/add/observable/fromEvent");
25976 require("rxjs/add/observable/of");
25977 require("rxjs/add/observable/zip");
25978 require("rxjs/add/operator/distinctUntilChanged");
25979 require("rxjs/add/operator/filter");
25980 require("rxjs/add/operator/first");
25981 require("rxjs/add/operator/map");
25982 require("rxjs/add/operator/merge");
25983 require("rxjs/add/operator/mergeMap");
25984 require("rxjs/add/operator/scan");
25985 require("rxjs/add/operator/switchMap");
25986 require("rxjs/add/operator/withLatestFrom");
25987 require("rxjs/add/operator/zip");
25988 var State_1 = require("../../State");
25989 var Render_1 = require("../../Render");
25990 var Utils_1 = require("../../Utils");
25991 var Component_1 = require("../../Component");
25992 var SliderState = /** @class */ (function () {
25993 function SliderState() {
25994 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
25995 this._imagePlaneScene = new Component_1.ImagePlaneScene();
25996 this._currentKey = null;
25997 this._previousKey = null;
25998 this._currentPano = false;
26000 this._glNeedsRender = false;
26001 this._domNeedsRender = true;
26004 Object.defineProperty(SliderState.prototype, "frameId", {
26006 return this._frameId;
26011 Object.defineProperty(SliderState.prototype, "curtain", {
26013 return this._curtain;
26018 Object.defineProperty(SliderState.prototype, "glNeedsRender", {
26020 return this._glNeedsRender;
26025 Object.defineProperty(SliderState.prototype, "domNeedsRender", {
26027 return this._domNeedsRender;
26032 Object.defineProperty(SliderState.prototype, "sliderVisible", {
26034 return this._sliderVisible;
26036 set: function (value) {
26037 this._sliderVisible = value;
26038 this._domNeedsRender = true;
26043 Object.defineProperty(SliderState.prototype, "disabled", {
26045 return this._currentKey == null ||
26046 this._previousKey == null ||
26052 SliderState.prototype.update = function (frame) {
26053 this._updateFrameId(frame.id);
26054 var needsRender = this._updateImagePlanes(frame.state);
26055 this._domNeedsRender = needsRender || this._domNeedsRender;
26056 needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
26057 this._glNeedsRender = needsRender || this._glNeedsRender;
26059 SliderState.prototype.updateTexture = function (image, node) {
26060 var imagePlanes = node.key === this._currentKey ?
26061 this._imagePlaneScene.imagePlanes :
26062 node.key === this._previousKey ?
26063 this._imagePlaneScene.imagePlanesOld :
26065 if (imagePlanes.length === 0) {
26068 this._glNeedsRender = true;
26069 for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
26070 var plane = imagePlanes_1[_i];
26071 var material = plane.material;
26072 var texture = material.uniforms.projectorTex.value;
26073 texture.image = image;
26074 texture.needsUpdate = true;
26077 SliderState.prototype.render = function (perspectiveCamera, renderer) {
26078 if (!this.disabled) {
26079 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
26081 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
26083 SliderState.prototype.dispose = function () {
26084 this._imagePlaneScene.clear();
26086 SliderState.prototype.clearGLNeedsRender = function () {
26087 this._glNeedsRender = false;
26089 SliderState.prototype.clearDomNeedsRender = function () {
26090 this._domNeedsRender = false;
26092 SliderState.prototype._updateFrameId = function (frameId) {
26093 this._frameId = frameId;
26095 SliderState.prototype._updateImagePlanes = function (state) {
26096 if (state.currentNode == null) {
26099 var needsRender = false;
26100 if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
26101 needsRender = true;
26102 this._previousKey = state.previousNode.key;
26103 this._imagePlaneScene.setImagePlanesOld([
26104 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
26107 if (this._currentKey !== state.currentNode.key) {
26108 needsRender = true;
26109 this._currentKey = state.currentNode.key;
26110 this._currentPano = state.currentNode.pano;
26111 this._imagePlaneScene.setImagePlanes([
26112 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
26114 if (!this.disabled) {
26115 this._updateBbox();
26118 return needsRender;
26120 SliderState.prototype._updateCurtain = function (alpha) {
26121 if (this.disabled ||
26122 Math.abs(this._curtain - alpha) < 0.001) {
26125 this._curtain = alpha;
26126 this._updateBbox();
26129 SliderState.prototype._updateBbox = function () {
26130 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
26131 var plane = _a[_i];
26132 var shaderMaterial = plane.material;
26133 var bbox = shaderMaterial.uniforms.bbox.value;
26134 bbox.z = this._curtain;
26137 return SliderState;
26139 var SliderComponent = /** @class */ (function (_super) {
26140 __extends(SliderComponent, _super);
26142 * Create a new slider component instance.
26143 * @class SliderComponent
26145 function SliderComponent(name, container, navigator, dom) {
26146 var _this = _super.call(this, name, container, navigator) || this;
26147 _this._dom = !!dom ? dom : new Utils_1.DOM();
26148 _this._sliderStateOperation$ = new Subject_1.Subject();
26149 _this._sliderStateCreator$ = new Subject_1.Subject();
26150 _this._sliderStateDisposer$ = new Subject_1.Subject();
26151 _this._sliderState$ = _this._sliderStateOperation$
26152 .scan(function (sliderState, operation) {
26153 return operation(sliderState);
26155 .filter(function (sliderState) {
26156 return sliderState != null;
26158 .distinctUntilChanged(undefined, function (sliderState) {
26159 return sliderState.frameId;
26161 _this._sliderStateCreator$
26163 return function (sliderState) {
26164 if (sliderState != null) {
26165 throw new Error("Multiple slider states can not be created at the same time");
26167 return new SliderState();
26170 .subscribe(_this._sliderStateOperation$);
26171 _this._sliderStateDisposer$
26173 return function (sliderState) {
26174 sliderState.dispose();
26178 .subscribe(_this._sliderStateOperation$);
26182 * Set the image keys.
26184 * Configures the component to show the image planes for the supplied image keys.
26186 * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
26188 SliderComponent.prototype.setKeys = function (keys) {
26189 this.configure({ keys: keys });
26192 * Set the initial position.
26194 * Configures the intial position of the slider. The inital position value will be used when the component is activated.
26196 * @param {number} initialPosition - Initial slider position.
26198 SliderComponent.prototype.setInitialPosition = function (initialPosition) {
26199 this.configure({ initialPosition: initialPosition });
26202 * Set the value controlling if the slider is visible.
26204 * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
26206 SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
26207 this.configure({ sliderVisible: sliderVisible });
26209 SliderComponent.prototype._activate = function () {
26211 this._sliderContainer = this._dom.createElement("div", "mapillary-js-slider-container", this._container.element);
26212 this._sliderWrapper = this._dom.createElement("div", "SliderWrapper", this._sliderContainer);
26213 this._sliderControl = this._dom.createElement("input", "SliderControl", this._sliderWrapper);
26214 this._sliderControl.setAttribute("type", "range");
26215 this._sliderControl.setAttribute("min", "0");
26216 this._sliderControl.setAttribute("max", "1000");
26217 this._sliderControl.style.visibility = "hidden";
26218 this._moveToHandler = function (e) {
26219 var curtain = Number(e.target.value) / 1000;
26220 _this._navigator.stateService.moveTo(curtain);
26222 this._sliderControl.addEventListener("input", this._moveToHandler);
26223 this._sliderControl.addEventListener("change", this._moveToHandler);
26224 Observable_1.Observable
26225 .combineLatest(this._navigator.stateService.state$, this._configuration$)
26227 .subscribe(function (_a) {
26228 var state = _a[0], configuration = _a[1];
26229 if (state === State_1.State.Traversing) {
26230 _this._navigator.stateService.wait();
26231 var position = configuration.initialPosition != null ? configuration.initialPosition : 1;
26232 _this._sliderControl.value = (1000 * position).toString();
26233 _this._navigator.stateService.moveTo(position);
26236 this._glRenderSubscription = this._sliderState$
26237 .map(function (sliderState) {
26241 frameId: sliderState.frameId,
26242 needsRender: sliderState.glNeedsRender,
26243 render: sliderState.render.bind(sliderState),
26244 stage: Render_1.GLRenderStage.Background,
26247 sliderState.clearGLNeedsRender();
26250 .subscribe(this._container.glRenderer.render$);
26251 this._domRenderSubscription = this._sliderState$
26252 .filter(function (sliderState) {
26253 return sliderState.domNeedsRender;
26255 .subscribe(function (sliderState) {
26256 _this._sliderControl.value = (1000 * sliderState.curtain).toString();
26257 var visibility = sliderState.disabled || !sliderState.sliderVisible ? "hidden" : "visible";
26258 _this._sliderControl.style.visibility = visibility;
26259 sliderState.clearDomNeedsRender();
26261 this._sliderStateCreator$.next(null);
26262 this._stateSubscription = this._navigator.stateService.currentState$
26263 .map(function (frame) {
26264 return function (sliderState) {
26265 sliderState.update(frame);
26266 return sliderState;
26269 .subscribe(this._sliderStateOperation$);
26270 this._setSliderVisibleSubscription = this._configuration$
26271 .map(function (configuration) {
26272 return configuration.sliderVisible == null || configuration.sliderVisible;
26274 .distinctUntilChanged()
26275 .map(function (sliderVisible) {
26276 return function (sliderState) {
26277 sliderState.sliderVisible = sliderVisible;
26278 return sliderState;
26281 .subscribe(this._sliderStateOperation$);
26282 this._setKeysSubscription = this._configuration$
26283 .filter(function (configuration) {
26284 return configuration.keys != null;
26286 .switchMap(function (configuration) {
26287 return Observable_1.Observable
26288 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
26289 .map(function (nodes) {
26290 return { background: nodes[0], foreground: nodes[1] };
26292 .zip(_this._navigator.stateService.currentState$.first())
26293 .map(function (nf) {
26294 return { nodes: nf[0], state: nf[1].state };
26297 .subscribe(function (co) {
26298 if (co.state.currentNode != null &&
26299 co.state.previousNode != null &&
26300 co.state.currentNode.key === co.nodes.foreground.key &&
26301 co.state.previousNode.key === co.nodes.background.key) {
26304 if (co.state.currentNode.key === co.nodes.background.key) {
26305 _this._navigator.stateService.setNodes([co.nodes.foreground]);
26308 if (co.state.currentNode.key === co.nodes.foreground.key &&
26309 co.state.trajectory.length === 1) {
26310 _this._navigator.stateService.prependNodes([co.nodes.background]);
26313 _this._navigator.stateService.setNodes([co.nodes.background]);
26314 _this._navigator.stateService.setNodes([co.nodes.foreground]);
26318 var previousNode$ = this._navigator.stateService.currentState$
26319 .map(function (frame) {
26320 return frame.state.previousNode;
26322 .filter(function (node) {
26323 return node != null;
26325 .distinctUntilChanged(undefined, function (node) {
26328 this._nodeSubscription = Observable_1.Observable
26329 .merge(previousNode$, this._navigator.stateService.currentNode$)
26330 .filter(function (node) {
26332 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
26333 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
26335 .mergeMap(function (node) {
26336 var baseImageSize = node.pano ?
26337 Utils_1.Settings.basePanoramaSize :
26338 Utils_1.Settings.baseImageSize;
26339 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
26340 return Observable_1.Observable.empty();
26342 return node.cacheImage$(Utils_1.Settings.maxImageSize)
26343 .map(function (n) {
26344 return [n.image, n];
26346 .catch(function (error, caught) {
26347 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
26348 return Observable_1.Observable.empty();
26351 .map(function (_a) {
26352 var element = _a[0], node = _a[1];
26353 return function (sliderState) {
26354 sliderState.updateTexture(element, node);
26355 return sliderState;
26358 .subscribe(this._sliderStateOperation$);
26360 SliderComponent.prototype._deactivate = function () {
26362 this._navigator.stateService.state$
26364 .subscribe(function (state) {
26365 if (state === State_1.State.Waiting) {
26366 _this._navigator.stateService.traverse();
26369 this._sliderStateDisposer$.next(null);
26370 this._setKeysSubscription.unsubscribe();
26371 this._setSliderVisibleSubscription.unsubscribe();
26372 this._stateSubscription.unsubscribe();
26373 this._glRenderSubscription.unsubscribe();
26374 this._domRenderSubscription.unsubscribe();
26375 this._nodeSubscription.unsubscribe();
26376 this.configure({ keys: null });
26377 this._sliderControl.removeEventListener("input", this._moveToHandler);
26378 this._sliderControl.removeEventListener("change", this._moveToHandler);
26379 this._container.element.removeChild(this._sliderContainer);
26380 this._moveToHandler = null;
26381 this._sliderControl = null;
26382 this._sliderWrapper = null;
26383 this._sliderContainer = null;
26385 SliderComponent.prototype._getDefaultConfiguration = function () {
26388 SliderComponent.prototype._catchCacheNode$ = function (key) {
26389 return this._navigator.graphService.cacheNode$(key)
26390 .catch(function (error, caught) {
26391 console.error("Failed to cache slider node (" + key + ")", error);
26392 return Observable_1.Observable.empty();
26395 SliderComponent.componentName = "slider";
26396 return SliderComponent;
26397 }(Component_1.Component));
26398 exports.SliderComponent = SliderComponent;
26399 Component_1.ComponentService.register(SliderComponent);
26400 exports.default = SliderComponent;
26402 },{"../../Component":281,"../../Render":287,"../../State":288,"../../Utils":291,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/fromEvent":42,"rxjs/add/observable/of":45,"rxjs/add/observable/zip":48,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/scan":75,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/withLatestFrom":87,"rxjs/add/operator/zip":88}],317:[function(require,module,exports){
26404 Object.defineProperty(exports, "__esModule", { value: true });
26406 (function (CoverState) {
26407 CoverState[CoverState["Hidden"] = 0] = "Hidden";
26408 CoverState[CoverState["Loading"] = 1] = "Loading";
26409 CoverState[CoverState["Visible"] = 2] = "Visible";
26410 })(CoverState = exports.CoverState || (exports.CoverState = {}));
26412 },{}],318:[function(require,module,exports){
26414 Object.defineProperty(exports, "__esModule", { value: true });
26415 var ICoverConfiguration_1 = require("./ICoverConfiguration");
26416 exports.CoverState = ICoverConfiguration_1.CoverState;
26418 },{"./ICoverConfiguration":317}],319:[function(require,module,exports){
26420 /// <reference path="../../../typings/index.d.ts" />
26421 var __extends = (this && this.__extends) || (function () {
26422 var extendStatics = Object.setPrototypeOf ||
26423 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26424 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26425 return function (d, b) {
26426 extendStatics(d, b);
26427 function __() { this.constructor = d; }
26428 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26431 Object.defineProperty(exports, "__esModule", { value: true });
26432 var Component_1 = require("../../Component");
26433 var Edge_1 = require("../../Edge");
26435 * The `KeyPlayHandler` allows the user to control the play behavior
26436 * using the following key commands:
26438 * `Spacebar`: Start or stop playing.
26439 * `SHIFT` + `D`: Switch direction.
26440 * `<`: Decrease speed.
26441 * `>`: Increase speed.
26445 * var keyboardComponent = viewer.getComponent("keyboard");
26447 * keyboardComponent.keyPlay.disable();
26448 * keyboardComponent.keyPlay.enable();
26450 * var isEnabled = keyboardComponent.keyPlay.isEnabled;
26453 var KeyPlayHandler = /** @class */ (function (_super) {
26454 __extends(KeyPlayHandler, _super);
26455 function KeyPlayHandler() {
26456 return _super !== null && _super.apply(this, arguments) || this;
26458 KeyPlayHandler.prototype._enable = function () {
26460 this._keyDownSubscription = this._container.keyboardService.keyDown$
26461 .withLatestFrom(this._navigator.playService.playing$, this._navigator.playService.direction$, this._navigator.playService.speed$, this._navigator.stateService.currentNode$
26462 .switchMap(function (node) {
26463 return node.sequenceEdges$;
26465 .subscribe(function (_a) {
26466 var event = _a[0], playing = _a[1], direction = _a[2], speed = _a[3], status = _a[4];
26467 if (event.altKey || event.ctrlKey || event.metaKey) {
26470 switch (event.key) {
26472 if (!event.shiftKey) {
26475 var newDirection = playing ?
26476 null : direction === Edge_1.EdgeDirection.Next ?
26477 Edge_1.EdgeDirection.Prev : direction === Edge_1.EdgeDirection.Prev ?
26478 Edge_1.EdgeDirection.Next : null;
26479 if (newDirection != null) {
26480 _this._navigator.playService.setDirection(newDirection);
26484 if (event.shiftKey) {
26488 _this._navigator.playService.stop();
26491 for (var _i = 0, _b = status.edges; _i < _b.length; _i++) {
26493 if (edge.data.direction === direction) {
26494 _this._navigator.playService.play();
26500 _this._navigator.playService.setSpeed(speed - 0.05);
26503 _this._navigator.playService.setSpeed(speed + 0.05);
26508 event.preventDefault();
26511 KeyPlayHandler.prototype._disable = function () {
26512 this._keyDownSubscription.unsubscribe();
26514 KeyPlayHandler.prototype._getConfiguration = function (enable) {
26515 return { keyZoom: enable };
26517 return KeyPlayHandler;
26518 }(Component_1.HandlerBase));
26519 exports.KeyPlayHandler = KeyPlayHandler;
26520 exports.default = KeyPlayHandler;
26522 },{"../../Component":281,"../../Edge":282}],320:[function(require,module,exports){
26524 /// <reference path="../../../typings/index.d.ts" />
26525 var __extends = (this && this.__extends) || (function () {
26526 var extendStatics = Object.setPrototypeOf ||
26527 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26528 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26529 return function (d, b) {
26530 extendStatics(d, b);
26531 function __() { this.constructor = d; }
26532 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26535 Object.defineProperty(exports, "__esModule", { value: true });
26536 require("rxjs/add/operator/switchMap");
26537 require("rxjs/add/operator/withLatestFrom");
26538 var Component_1 = require("../../Component");
26539 var Edge_1 = require("../../Edge");
26541 * The `KeySequenceNavigationHandler` allows the user to navigate through a sequence using the
26542 * following key commands:
26544 * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
26545 * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
26549 * var keyboardComponent = viewer.getComponent("keyboard");
26551 * keyboardComponent.keySequenceNavigation.disable();
26552 * keyboardComponent.keySequenceNavigation.enable();
26554 * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
26557 var KeySequenceNavigationHandler = /** @class */ (function (_super) {
26558 __extends(KeySequenceNavigationHandler, _super);
26559 function KeySequenceNavigationHandler() {
26560 return _super !== null && _super.apply(this, arguments) || this;
26562 KeySequenceNavigationHandler.prototype._enable = function () {
26564 var sequenceEdges$ = this._navigator.stateService.currentNode$
26565 .switchMap(function (node) {
26566 return node.sequenceEdges$;
26568 this._keyDownSubscription = this._container.keyboardService.keyDown$
26569 .withLatestFrom(sequenceEdges$)
26570 .subscribe(function (_a) {
26571 var event = _a[0], edgeStatus = _a[1];
26572 var direction = null;
26573 switch (event.keyCode) {
26575 direction = Edge_1.EdgeDirection.Next;
26578 direction = Edge_1.EdgeDirection.Prev;
26583 event.preventDefault();
26584 if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
26587 for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
26589 if (edge.data.direction === direction) {
26590 _this._navigator.moveToKey$(edge.to)
26591 .subscribe(function (n) { return; }, function (e) { console.error(e); });
26597 KeySequenceNavigationHandler.prototype._disable = function () {
26598 this._keyDownSubscription.unsubscribe();
26600 KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
26601 return { keySequenceNavigation: enable };
26603 return KeySequenceNavigationHandler;
26604 }(Component_1.HandlerBase));
26605 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
26606 exports.default = KeySequenceNavigationHandler;
26608 },{"../../Component":281,"../../Edge":282,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/withLatestFrom":87}],321:[function(require,module,exports){
26610 /// <reference path="../../../typings/index.d.ts" />
26611 var __extends = (this && this.__extends) || (function () {
26612 var extendStatics = Object.setPrototypeOf ||
26613 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26614 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26615 return function (d, b) {
26616 extendStatics(d, b);
26617 function __() { this.constructor = d; }
26618 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26621 Object.defineProperty(exports, "__esModule", { value: true });
26622 require("rxjs/add/operator/switchMap");
26623 require("rxjs/add/operator/withLatestFrom");
26624 var Component_1 = require("../../Component");
26625 var Edge_1 = require("../../Edge");
26627 * The `KeySpatialNavigationHandler` allows the user to navigate through a sequence using the
26628 * following key commands:
26630 * `Up Arrow`: Step forward.
26631 * `Down Arrow`: Step backward.
26632 * `Left Arrow`: Step to the left.
26633 * `Rigth Arrow`: Step to the right.
26634 * `SHIFT` + `Down Arrow`: Turn around.
26635 * `SHIFT` + `Left Arrow`: Turn to the left.
26636 * `SHIFT` + `Rigth Arrow`: Turn to the right.
26640 * var keyboardComponent = viewer.getComponent("keyboard");
26642 * keyboardComponent.keySpatialNavigation.disable();
26643 * keyboardComponent.keySpatialNavigation.enable();
26645 * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
26648 var KeySpatialNavigationHandler = /** @class */ (function (_super) {
26649 __extends(KeySpatialNavigationHandler, _super);
26650 function KeySpatialNavigationHandler(component, container, navigator, spatial) {
26651 var _this = _super.call(this, component, container, navigator) || this;
26652 _this._spatial = spatial;
26655 KeySpatialNavigationHandler.prototype._enable = function () {
26657 var spatialEdges$ = this._navigator.stateService.currentNode$
26658 .switchMap(function (node) {
26659 return node.spatialEdges$;
26661 this._keyDownSubscription = this._container.keyboardService.keyDown$
26662 .withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$)
26663 .subscribe(function (_a) {
26664 var event = _a[0], edgeStatus = _a[1], frame = _a[2];
26665 var pano = frame.state.currentNode.pano;
26666 var direction = null;
26667 switch (event.keyCode) {
26669 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
26672 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
26675 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
26678 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
26683 event.preventDefault();
26684 if (event.altKey || !edgeStatus.cached ||
26685 (event.shiftKey && pano)) {
26689 _this._moveDir(direction, edgeStatus);
26693 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
26694 shifts[Edge_1.EdgeDirection.StepForward] = 0;
26695 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
26696 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
26697 var phi = _this._rotationFromCamera(frame.state.camera).phi;
26698 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
26699 var threshold = Math.PI / 4;
26700 var edges = edgeStatus.edges.filter(function (e) {
26701 return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
26703 var smallestAngle = Number.MAX_VALUE;
26705 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
26706 var edge = edges_1[_i];
26707 var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
26708 if (angle < Math.min(smallestAngle, threshold)) {
26709 smallestAngle = angle;
26713 if (toKey == null) {
26716 _this._moveToKey(toKey);
26720 KeySpatialNavigationHandler.prototype._disable = function () {
26721 this._keyDownSubscription.unsubscribe();
26723 KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
26724 return { keySpatialNavigation: enable };
26726 KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
26727 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26729 if (edge.data.direction === direction) {
26730 this._moveToKey(edge.to);
26735 KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
26736 this._navigator.moveToKey$(key)
26737 .subscribe(function (n) { }, function (e) { console.error(e); });
26739 KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
26740 var direction = camera.lookat.clone().sub(camera.position);
26741 var upProjection = direction.clone().dot(camera.up);
26742 var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
26743 var phi = Math.atan2(planeProjection.y, planeProjection.x);
26744 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
26745 return { phi: phi, theta: theta };
26747 return KeySpatialNavigationHandler;
26748 }(Component_1.HandlerBase));
26749 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
26750 exports.default = KeySpatialNavigationHandler;
26752 },{"../../Component":281,"../../Edge":282,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/withLatestFrom":87}],322:[function(require,module,exports){
26754 /// <reference path="../../../typings/index.d.ts" />
26755 var __extends = (this && this.__extends) || (function () {
26756 var extendStatics = Object.setPrototypeOf ||
26757 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26758 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26759 return function (d, b) {
26760 extendStatics(d, b);
26761 function __() { this.constructor = d; }
26762 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26765 Object.defineProperty(exports, "__esModule", { value: true });
26766 require("rxjs/add/operator/withLatestFrom");
26767 var Component_1 = require("../../Component");
26769 * The `KeyZoomHandler` allows the user to zoom in and out using the
26770 * following key commands:
26777 * var keyboardComponent = viewer.getComponent("keyboard");
26779 * keyboardComponent.keyZoom.disable();
26780 * keyboardComponent.keyZoom.enable();
26782 * var isEnabled = keyboardComponent.keyZoom.isEnabled;
26785 var KeyZoomHandler = /** @class */ (function (_super) {
26786 __extends(KeyZoomHandler, _super);
26787 function KeyZoomHandler(component, container, navigator, viewportCoords) {
26788 var _this = _super.call(this, component, container, navigator) || this;
26789 _this._viewportCoords = viewportCoords;
26792 KeyZoomHandler.prototype._enable = function () {
26794 this._keyDownSubscription = this._container.keyboardService.keyDown$
26795 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
26796 .subscribe(function (_a) {
26797 var event = _a[0], render = _a[1], transform = _a[2];
26798 if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
26802 switch (event.key) {
26812 event.preventDefault();
26813 var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
26814 var reference = transform.projectBasic(unprojected.toArray());
26815 _this._navigator.stateService.zoomIn(delta, reference);
26818 KeyZoomHandler.prototype._disable = function () {
26819 this._keyDownSubscription.unsubscribe();
26821 KeyZoomHandler.prototype._getConfiguration = function (enable) {
26822 return { keyZoom: enable };
26824 return KeyZoomHandler;
26825 }(Component_1.HandlerBase));
26826 exports.KeyZoomHandler = KeyZoomHandler;
26827 exports.default = KeyZoomHandler;
26829 },{"../../Component":281,"rxjs/add/operator/withLatestFrom":87}],323:[function(require,module,exports){
26831 var __extends = (this && this.__extends) || (function () {
26832 var extendStatics = Object.setPrototypeOf ||
26833 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26834 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26835 return function (d, b) {
26836 extendStatics(d, b);
26837 function __() { this.constructor = d; }
26838 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26841 Object.defineProperty(exports, "__esModule", { value: true });
26842 var Component_1 = require("../../Component");
26843 var Geo_1 = require("../../Geo");
26845 * @class KeyboardComponent
26847 * @classdesc Component for keyboard event handling.
26849 * To retrive and use the keyboard component
26853 * var viewer = new Mapillary.Viewer(
26858 * var keyboardComponent = viewer.getComponent("keyboard");
26861 var KeyboardComponent = /** @class */ (function (_super) {
26862 __extends(KeyboardComponent, _super);
26863 function KeyboardComponent(name, container, navigator) {
26864 var _this = _super.call(this, name, container, navigator) || this;
26865 _this._keyPlayHandler = new Component_1.KeyPlayHandler(_this, container, navigator);
26866 _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
26867 _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
26868 _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
26871 Object.defineProperty(KeyboardComponent.prototype, "keyPlay", {
26875 * @returns {KeyPlayHandler} The key play handler.
26878 return this._keyPlayHandler;
26883 Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
26885 * Get key sequence navigation.
26887 * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
26890 return this._keySequenceNavigationHandler;
26895 Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
26899 * @returns {KeySpatialNavigationHandler} The spatial handler.
26902 return this._keySpatialNavigationHandler;
26907 Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
26911 * @returns {KeyZoomHandler} The key zoom handler.
26914 return this._keyZoomHandler;
26919 KeyboardComponent.prototype._activate = function () {
26921 this._configurationSubscription = this._configuration$
26922 .subscribe(function (configuration) {
26923 if (configuration.keyPlay) {
26924 _this._keyPlayHandler.enable();
26927 _this._keyPlayHandler.disable();
26929 if (configuration.keySequenceNavigation) {
26930 _this._keySequenceNavigationHandler.enable();
26933 _this._keySequenceNavigationHandler.disable();
26935 if (configuration.keySpatialNavigation) {
26936 _this._keySpatialNavigationHandler.enable();
26939 _this._keySpatialNavigationHandler.disable();
26941 if (configuration.keyZoom) {
26942 _this._keyZoomHandler.enable();
26945 _this._keyZoomHandler.disable();
26949 KeyboardComponent.prototype._deactivate = function () {
26950 this._configurationSubscription.unsubscribe();
26951 this._keyPlayHandler.disable();
26952 this._keySequenceNavigationHandler.disable();
26953 this._keySpatialNavigationHandler.disable();
26954 this._keyZoomHandler.disable();
26956 KeyboardComponent.prototype._getDefaultConfiguration = function () {
26957 return { keyPlay: true, keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
26959 KeyboardComponent.componentName = "keyboard";
26960 return KeyboardComponent;
26961 }(Component_1.Component));
26962 exports.KeyboardComponent = KeyboardComponent;
26963 Component_1.ComponentService.register(KeyboardComponent);
26964 exports.default = KeyboardComponent;
26966 },{"../../Component":281,"../../Geo":284}],324:[function(require,module,exports){
26968 Object.defineProperty(exports, "__esModule", { value: true });
26969 var MarkerComponent_1 = require("./MarkerComponent");
26970 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
26971 var SimpleMarker_1 = require("./marker/SimpleMarker");
26972 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
26973 var CircleMarker_1 = require("./marker/CircleMarker");
26974 exports.CircleMarker = CircleMarker_1.CircleMarker;
26976 },{"./MarkerComponent":325,"./marker/CircleMarker":328,"./marker/SimpleMarker":330}],325:[function(require,module,exports){
26978 /// <reference path="../../../typings/index.d.ts" />
26979 var __extends = (this && this.__extends) || (function () {
26980 var extendStatics = Object.setPrototypeOf ||
26981 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26982 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26983 return function (d, b) {
26984 extendStatics(d, b);
26985 function __() { this.constructor = d; }
26986 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26989 Object.defineProperty(exports, "__esModule", { value: true });
26990 var THREE = require("three");
26991 var when = require("when");
26992 var Observable_1 = require("rxjs/Observable");
26993 require("rxjs/add/observable/combineLatest");
26994 require("rxjs/add/operator/distinctUntilChanged");
26995 require("rxjs/add/operator/map");
26996 var Component_1 = require("../../Component");
26997 var Render_1 = require("../../Render");
26998 var Graph_1 = require("../../Graph");
26999 var Geo_1 = require("../../Geo");
27001 * @class MarkerComponent
27003 * @classdesc Component for showing and editing 3D marker objects.
27005 * The `add` method is used for adding new markers or replacing
27006 * markers already in the set.
27008 * If a marker already in the set has the same
27009 * id as one of the markers added, the old marker will be removed and
27010 * the added marker will take its place.
27012 * It is not possible to update markers in the set by updating any properties
27013 * directly on the marker object. Markers need to be replaced by
27014 * re-adding them for updates to geographic position or configuration
27017 * Markers added to the marker component can be either interactive
27018 * or non-interactive. Different marker types define their behavior.
27019 * Markers with interaction support can be configured with options
27020 * to respond to dragging inside the viewer and be detected when
27021 * retrieving markers from pixel points with the `getMarkerIdAt` method.
27023 * To retrive and use the marker component
27027 * var viewer = new Mapillary.Viewer(
27031 * { component: { marker: true } });
27033 * var markerComponent = viewer.getComponent("marker");
27036 var MarkerComponent = /** @class */ (function (_super) {
27037 __extends(MarkerComponent, _super);
27038 function MarkerComponent(name, container, navigator) {
27039 var _this = _super.call(this, name, container, navigator) || this;
27040 _this._relativeGroundAltitude = -2;
27041 _this._geoCoords = new Geo_1.GeoCoords();
27042 _this._graphCalculator = new Graph_1.GraphCalculator();
27043 _this._markerScene = new Component_1.MarkerScene();
27044 _this._markerSet = new Component_1.MarkerSet();
27045 _this._viewportCoords = new Geo_1.ViewportCoords();
27049 * Add markers to the marker set or replace markers in the marker set.
27051 * @description If a marker already in the set has the same
27052 * id as one of the markers added, the old marker will be removed
27053 * the added marker will take its place.
27055 * Any marker inside the visible bounding bbox
27056 * will be initialized and placed in the viewer.
27058 * @param {Array<Marker>} markers - Markers to add.
27060 * @example ```markerComponent.add([marker1, marker2]);```
27062 MarkerComponent.prototype.add = function (markers) {
27063 this._markerSet.add(markers);
27066 * Returns the marker in the marker set with the specified id, or
27067 * undefined if the id matches no marker.
27069 * @param {string} markerId - Id of the marker.
27071 * @example ```var marker = markerComponent.get("markerId");```
27074 MarkerComponent.prototype.get = function (markerId) {
27075 return this._markerSet.get(markerId);
27078 * Returns an array of all markers.
27080 * @example ```var markers = markerComponent.getAll();```
27082 MarkerComponent.prototype.getAll = function () {
27083 return this._markerSet.getAll();
27086 * Returns the id of the interactive marker closest to the current camera
27087 * position at the specified point.
27089 * @description Notice that the pixelPoint argument requires x, y
27090 * coordinates from pixel space.
27092 * With this function, you can use the coordinates provided by mouse
27093 * events to get information out of the marker component.
27095 * If no interactive geometry of an interactive marker exist at the pixel
27096 * point, `null` will be returned.
27098 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
27099 * @returns {string} Id of the interactive marker closest to the camera. If no
27100 * interactive marker exist at the pixel point, `null` will be returned.
27104 * markerComponent.getMarkerIdAt([100, 100])
27105 * .then((markerId) => { console.log(markerId); });
27108 MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
27110 return when.promise(function (resolve, reject) {
27111 _this._container.renderService.renderCamera$
27113 .map(function (render) {
27114 var viewport = _this._viewportCoords
27115 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
27116 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
27119 .subscribe(function (id) {
27121 }, function (error) {
27127 * Check if a marker exist in the marker set.
27129 * @param {string} markerId - Id of the marker.
27131 * @example ```var markerExists = markerComponent.has("markerId");```
27133 MarkerComponent.prototype.has = function (markerId) {
27134 return this._markerSet.has(markerId);
27137 * Remove markers with the specified ids from the marker set.
27139 * @param {Array<string>} markerIds - Ids for markers to remove.
27141 * @example ```markerComponent.remove(["id-1", "id-2"]);```
27143 MarkerComponent.prototype.remove = function (markerIds) {
27144 this._markerSet.remove(markerIds);
27147 * Remove all markers from the marker set.
27149 * @example ```markerComponent.removeAll();```
27151 MarkerComponent.prototype.removeAll = function () {
27152 this._markerSet.removeAll();
27154 MarkerComponent.prototype._activate = function () {
27156 var groundAltitude$ = this._navigator.stateService.currentState$
27157 .map(function (frame) {
27158 return frame.state.camera.position.z + _this._relativeGroundAltitude;
27160 .distinctUntilChanged(function (a1, a2) {
27161 return Math.abs(a1 - a2) < 0.01;
27165 var geoInitiated$ = Observable_1.Observable
27166 .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
27168 .map(function () { })
27171 var clampedConfiguration$ = this._configuration$
27172 .map(function (configuration) {
27173 return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
27175 var currentlatLon$ = this._navigator.stateService.currentNode$
27176 .map(function (node) { return node.latLon; })
27179 var visibleBBox$ = Observable_1.Observable
27180 .combineLatest(clampedConfiguration$, currentlatLon$)
27181 .map(function (_a) {
27182 var configuration = _a[0], latLon = _a[1];
27183 return _this._graphCalculator
27184 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
27188 var visibleMarkers$ = Observable_1.Observable
27189 .combineLatest(Observable_1.Observable
27190 .of(this._markerSet)
27191 .concat(this._markerSet.changed$), visibleBBox$)
27192 .map(function (_a) {
27193 var set = _a[0], bbox = _a[1];
27194 return set.search(bbox);
27196 this._setChangedSubscription = geoInitiated$
27197 .switchMap(function () {
27198 return visibleMarkers$
27199 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
27201 .subscribe(function (_a) {
27202 var markers = _a[0], reference = _a[1], alt = _a[2];
27203 var geoCoords = _this._geoCoords;
27204 var markerScene = _this._markerScene;
27205 var sceneMarkers = markerScene.markers;
27206 var markersToRemove = Object.assign({}, sceneMarkers);
27207 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
27208 var marker = markers_1[_i];
27209 if (marker.id in sceneMarkers) {
27210 delete markersToRemove[marker.id];
27213 var point3d = geoCoords
27214 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27215 markerScene.add(marker, point3d);
27218 for (var id in markersToRemove) {
27219 if (!markersToRemove.hasOwnProperty(id)) {
27222 markerScene.remove(id);
27225 this._markersUpdatedSubscription = geoInitiated$
27226 .switchMap(function () {
27227 return _this._markerSet.updated$
27228 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
27230 .subscribe(function (_a) {
27231 var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
27232 var geoCoords = _this._geoCoords;
27233 var markerScene = _this._markerScene;
27234 for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
27235 var marker = markers_2[_i];
27236 var exists = markerScene.has(marker.id);
27237 var visible = marker.latLon.lat > sw.lat &&
27238 marker.latLon.lat < ne.lat &&
27239 marker.latLon.lon > sw.lon &&
27240 marker.latLon.lon < ne.lon;
27242 var point3d = geoCoords
27243 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27244 markerScene.add(marker, point3d);
27246 else if (!visible && exists) {
27247 markerScene.remove(marker.id);
27251 this._referenceSubscription = this._navigator.stateService.reference$
27253 .withLatestFrom(groundAltitude$)
27254 .subscribe(function (_a) {
27255 var reference = _a[0], alt = _a[1];
27256 var geoCoords = _this._geoCoords;
27257 var markerScene = _this._markerScene;
27258 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
27259 var marker = _b[_i];
27260 var point3d = geoCoords
27261 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27262 markerScene.update(marker.id, point3d);
27265 this._adjustHeightSubscription = groundAltitude$
27267 .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
27268 .subscribe(function (_a) {
27269 var alt = _a[0], reference = _a[1], latLon = _a[2];
27270 var geoCoords = _this._geoCoords;
27271 var markerScene = _this._markerScene;
27272 var position = geoCoords
27273 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27274 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
27275 var marker = _b[_i];
27276 var point3d = geoCoords
27277 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27278 var distanceX = point3d[0] - position[0];
27279 var distanceY = point3d[1] - position[1];
27280 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
27281 if (groundDistance > 50) {
27284 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
27287 this._renderSubscription = this._navigator.stateService.currentState$
27288 .map(function (frame) {
27289 var scene = _this._markerScene;
27294 needsRender: scene.needsRender,
27295 render: scene.render.bind(scene),
27296 stage: Render_1.GLRenderStage.Foreground,
27300 .subscribe(this._container.glRenderer.render$);
27301 var hoveredMarkerId$ = Observable_1.Observable
27302 .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
27303 .map(function (_a) {
27304 var render = _a[0], event = _a[1];
27305 var element = _this._container.element;
27306 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
27307 var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
27308 var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
27313 var draggingStarted$ = this._container.mouseService
27314 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
27315 .map(function (event) {
27318 var draggingStopped$ = this._container.mouseService
27319 .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
27320 .map(function (event) {
27323 var filteredDragging$ = Observable_1.Observable
27324 .merge(draggingStarted$, draggingStopped$)
27326 this._dragEventSubscription = draggingStarted$
27327 .withLatestFrom(hoveredMarkerId$)
27328 .merge(Observable_1.Observable
27329 .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
27330 .startWith([false, null])
27332 .subscribe(function (_a) {
27333 var previous = _a[0], current = _a[1];
27334 var dragging = current[0];
27335 var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
27336 var id = dragging ? current[1] : previous[1];
27337 var marker = _this._markerScene.get(id);
27338 var markerEvent = { marker: marker, target: _this, type: eventType };
27339 _this.fire(eventType, markerEvent);
27341 var mouseDown$ = Observable_1.Observable
27342 .merge(this._container.mouseService.mouseDown$
27343 .map(function (event) { return true; }), this._container.mouseService.documentMouseUp$
27344 .map(function (event) { return false; }))
27346 this._mouseClaimSubscription = Observable_1.Observable
27347 .combineLatest(this._container.mouseService.active$, hoveredMarkerId$.distinctUntilChanged(), mouseDown$, filteredDragging$)
27348 .map(function (_a) {
27349 var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
27350 return (!active && markerId != null && mouseDown) || filteredDragging;
27352 .distinctUntilChanged()
27353 .subscribe(function (claim) {
27355 _this._container.mouseService.claimMouse(_this._name, 1);
27356 _this._container.mouseService.claimWheel(_this._name, 1);
27359 _this._container.mouseService.unclaimMouse(_this._name);
27360 _this._container.mouseService.unclaimWheel(_this._name);
27363 var offset$ = this._container.mouseService
27364 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
27365 .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
27366 .map(function (_a) {
27367 var e = _a[0], id = _a[1], r = _a[2];
27368 var marker = _this._markerScene.get(id);
27369 var element = _this._container.element;
27370 var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
27371 var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
27372 var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
27373 return [marker, offset, r];
27377 this._updateMarkerSubscription = this._container.mouseService
27378 .filtered$(this._name, this._container.mouseService.mouseDrag$)
27379 .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
27380 .subscribe(function (_a) {
27381 var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
27382 if (!_this._markerScene.has(marker.id)) {
27385 var element = _this._container.element;
27386 var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
27387 var groundX = canvasX - offset[0];
27388 var groundY = canvasY - offset[1];
27389 var _d = _this._viewportCoords
27390 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
27391 var direction = new THREE.Vector3(viewportX, viewportY, 1)
27392 .unproject(render.perspective)
27393 .sub(render.perspective.position)
27395 var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
27396 if (distance < 0) {
27399 var intersection = direction
27401 .multiplyScalar(distance)
27402 .add(render.perspective.position);
27403 intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
27404 var _e = _this._geoCoords
27405 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
27406 _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
27407 _this._markerSet.update(marker);
27408 var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
27409 _this.fire(MarkerComponent.changed, markerEvent);
27412 MarkerComponent.prototype._deactivate = function () {
27413 this._adjustHeightSubscription.unsubscribe();
27414 this._dragEventSubscription.unsubscribe();
27415 this._markersUpdatedSubscription.unsubscribe();
27416 this._mouseClaimSubscription.unsubscribe();
27417 this._referenceSubscription.unsubscribe();
27418 this._renderSubscription.unsubscribe();
27419 this._setChangedSubscription.unsubscribe();
27420 this._updateMarkerSubscription.unsubscribe();
27421 this._markerScene.clear();
27423 MarkerComponent.prototype._getDefaultConfiguration = function () {
27424 return { visibleBBoxSize: 100 };
27426 MarkerComponent.componentName = "marker";
27428 * Fired when the position of a marker is changed.
27430 * @type {IMarkerEvent} markerEvent - Marker event data.
27433 * markerComponent.on("changed", function(e) {
27434 * console.log(e.marker.id, e.marker.latLon);
27438 MarkerComponent.changed = "changed";
27440 * Fired when a marker drag interaction starts.
27442 * @type {IMarkerEvent} markerEvent - Marker event data.
27445 * markerComponent.on("dragstart", function(e) {
27446 * console.log(e.marker.id, e.marker.latLon);
27450 MarkerComponent.dragstart = "dragstart";
27452 * Fired when a marker drag interaction ends.
27454 * @type {IMarkerEvent} markerEvent - Marker event data.
27457 * markerComponent.on("dragend", function(e) {
27458 * console.log(e.marker.id, e.marker.latLon);
27462 MarkerComponent.dragend = "dragend";
27463 return MarkerComponent;
27464 }(Component_1.Component));
27465 exports.MarkerComponent = MarkerComponent;
27466 Component_1.ComponentService.register(MarkerComponent);
27467 exports.default = MarkerComponent;
27469 },{"../../Component":281,"../../Geo":284,"../../Graph":285,"../../Render":287,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"three":231,"when":278}],326:[function(require,module,exports){
27471 /// <reference path="../../../typings/index.d.ts" />
27472 Object.defineProperty(exports, "__esModule", { value: true });
27473 var THREE = require("three");
27474 var MarkerScene = /** @class */ (function () {
27475 function MarkerScene(scene, raycaster) {
27476 this._needsRender = false;
27477 this._interactiveObjects = [];
27478 this._markers = {};
27479 this._objectMarkers = {};
27480 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
27481 this._scene = !!scene ? scene : new THREE.Scene();
27483 Object.defineProperty(MarkerScene.prototype, "markers", {
27485 return this._markers;
27490 Object.defineProperty(MarkerScene.prototype, "needsRender", {
27492 return this._needsRender;
27497 MarkerScene.prototype.add = function (marker, position) {
27498 if (marker.id in this._markers) {
27499 this._dispose(marker.id);
27501 marker.createGeometry(position);
27502 this._scene.add(marker.geometry);
27503 this._markers[marker.id] = marker;
27504 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
27505 var interactiveObject = _a[_i];
27506 this._interactiveObjects.push(interactiveObject);
27507 this._objectMarkers[interactiveObject.uuid] = marker.id;
27509 this._needsRender = true;
27511 MarkerScene.prototype.clear = function () {
27512 for (var id in this._markers) {
27513 if (!this._markers.hasOwnProperty) {
27518 this._needsRender = true;
27520 MarkerScene.prototype.get = function (id) {
27521 return this._markers[id];
27523 MarkerScene.prototype.getAll = function () {
27526 .keys(this._markers)
27527 .map(function (id) { return _this._markers[id]; });
27529 MarkerScene.prototype.has = function (id) {
27530 return id in this._markers;
27532 MarkerScene.prototype.intersectObjects = function (_a, camera) {
27533 var viewportX = _a[0], viewportY = _a[1];
27534 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
27535 var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
27536 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
27537 var intersect = intersects_1[_i];
27538 if (intersect.object.uuid in this._objectMarkers) {
27539 return this._objectMarkers[intersect.object.uuid];
27544 MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
27545 if (!(id in this._markers)) {
27548 this._markers[id].lerpAltitude(alt, alpha);
27549 this._needsRender = true;
27551 MarkerScene.prototype.remove = function (id) {
27552 if (!(id in this._markers)) {
27556 this._needsRender = true;
27558 MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
27559 renderer.render(this._scene, perspectiveCamera);
27560 this._needsRender = false;
27562 MarkerScene.prototype.update = function (id, position, latLon) {
27563 if (!(id in this._markers)) {
27566 var marker = this._markers[id];
27567 marker.updatePosition(position, latLon);
27568 this._needsRender = true;
27570 MarkerScene.prototype._dispose = function (id) {
27571 var marker = this._markers[id];
27572 this._scene.remove(marker.geometry);
27573 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
27574 var interactiveObject = _a[_i];
27575 var index = this._interactiveObjects.indexOf(interactiveObject);
27576 if (index !== -1) {
27577 this._interactiveObjects.splice(index, 1);
27580 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
27582 delete this._objectMarkers[interactiveObject.uuid];
27584 marker.disposeGeometry();
27585 delete this._markers[id];
27587 return MarkerScene;
27589 exports.MarkerScene = MarkerScene;
27590 exports.default = MarkerScene;
27592 },{"three":231}],327:[function(require,module,exports){
27594 /// <reference path="../../../typings/index.d.ts" />
27595 Object.defineProperty(exports, "__esModule", { value: true });
27596 var rbush = require("rbush");
27597 var Subject_1 = require("rxjs/Subject");
27598 require("rxjs/add/operator/map");
27599 require("rxjs/add/operator/publishReplay");
27600 require("rxjs/add/operator/scan");
27601 var MarkerSet = /** @class */ (function () {
27602 function MarkerSet() {
27604 this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
27605 this._indexChanged$ = new Subject_1.Subject();
27606 this._updated$ = new Subject_1.Subject();
27608 Object.defineProperty(MarkerSet.prototype, "changed$", {
27610 return this._indexChanged$;
27615 Object.defineProperty(MarkerSet.prototype, "updated$", {
27617 return this._updated$;
27622 MarkerSet.prototype.add = function (markers) {
27624 var hash = this._hash;
27625 var index = this._index;
27626 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
27627 var marker = markers_1[_i];
27628 var id = marker.id;
27630 index.remove(hash[id]);
27631 updated.push(marker);
27634 lat: marker.latLon.lat,
27635 lon: marker.latLon.lon,
27639 index.insert(item);
27641 if (updated.length > 0) {
27642 this._updated$.next(updated);
27644 if (markers.length > updated.length) {
27645 this._indexChanged$.next(this);
27648 MarkerSet.prototype.has = function (id) {
27649 return id in this._hash;
27651 MarkerSet.prototype.get = function (id) {
27652 return this.has(id) ? this._hash[id].marker : undefined;
27654 MarkerSet.prototype.getAll = function () {
27657 .map(function (indexItem) {
27658 return indexItem.marker;
27661 MarkerSet.prototype.remove = function (ids) {
27662 var hash = this._hash;
27663 var index = this._index;
27664 var changed = false;
27665 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
27666 var id = ids_1[_i];
27667 if (!(id in hash)) {
27670 var item = hash[id];
27671 index.remove(item);
27676 this._indexChanged$.next(this);
27679 MarkerSet.prototype.removeAll = function () {
27681 this._index.clear();
27682 this._indexChanged$.next(this);
27684 MarkerSet.prototype.search = function (_a) {
27685 var sw = _a[0], ne = _a[1];
27687 .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
27688 .map(function (indexItem) {
27689 return indexItem.marker;
27692 MarkerSet.prototype.update = function (marker) {
27693 var hash = this._hash;
27694 var index = this._index;
27695 var id = marker.id;
27696 if (!(id in hash)) {
27699 index.remove(hash[id]);
27701 lat: marker.latLon.lat,
27702 lon: marker.latLon.lon,
27706 index.insert(item);
27710 exports.MarkerSet = MarkerSet;
27711 exports.default = MarkerSet;
27713 },{"rbush":25,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75}],328:[function(require,module,exports){
27715 /// <reference path="../../../../typings/index.d.ts" />
27716 var __extends = (this && this.__extends) || (function () {
27717 var extendStatics = Object.setPrototypeOf ||
27718 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27719 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27720 return function (d, b) {
27721 extendStatics(d, b);
27722 function __() { this.constructor = d; }
27723 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27726 Object.defineProperty(exports, "__esModule", { value: true });
27727 var THREE = require("three");
27728 var Component_1 = require("../../../Component");
27730 * @class CircleMarker
27732 * @classdesc Non-interactive marker with a flat circle shape. The circle
27733 * marker can not be configured to be interactive.
27735 * Circle marker properties can not be updated after creation.
27737 * To create and add one `CircleMarker` with default configuration
27738 * and one with configuration use
27742 * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
27744 * { lat: 0, lon: 0, });
27746 * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
27748 * { lat: 0, lon: 0, },
27755 * markerComponent.add([defaultMarker, configuredMarker]);
27758 var CircleMarker = /** @class */ (function (_super) {
27759 __extends(CircleMarker, _super);
27760 function CircleMarker(id, latLon, options) {
27761 var _this = _super.call(this, id, latLon) || this;
27762 options = !!options ? options : {};
27763 _this._color = options.color != null ? options.color : 0xffffff;
27764 _this._opacity = options.opacity != null ? options.opacity : 0.4;
27765 _this._radius = options.radius != null ? options.radius : 1;
27768 CircleMarker.prototype._createGeometry = function (position) {
27769 var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
27770 color: this._color,
27771 opacity: this._opacity,
27774 circle.up.fromArray([0, 0, 1]);
27775 circle.renderOrder = -1;
27776 var group = new THREE.Object3D();
27778 group.position.fromArray(position);
27779 this._geometry = group;
27781 CircleMarker.prototype._disposeGeometry = function () {
27782 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
27784 mesh.geometry.dispose();
27785 mesh.material.dispose();
27788 CircleMarker.prototype._getInteractiveObjects = function () {
27791 return CircleMarker;
27792 }(Component_1.Marker));
27793 exports.CircleMarker = CircleMarker;
27794 exports.default = CircleMarker;
27796 },{"../../../Component":281,"three":231}],329:[function(require,module,exports){
27798 /// <reference path="../../../../typings/index.d.ts" />
27799 Object.defineProperty(exports, "__esModule", { value: true });
27803 * @classdesc Represents an abstract marker class that should be extended
27804 * by marker implementations used in the marker component.
27806 var Marker = /** @class */ (function () {
27807 function Marker(id, latLon) {
27809 this._latLon = latLon;
27811 Object.defineProperty(Marker.prototype, "id", {
27814 * @returns {string} The id of the marker.
27822 Object.defineProperty(Marker.prototype, "geometry", {
27824 return this._geometry;
27829 Object.defineProperty(Marker.prototype, "latLon", {
27832 * @returns {ILatLon} The geographic coordinates of the marker.
27835 return this._latLon;
27840 Marker.prototype.createGeometry = function (position) {
27841 if (!!this._geometry) {
27844 this._createGeometry(position);
27845 // update matrix world if raycasting occurs before first render
27846 this._geometry.updateMatrixWorld(true);
27848 Marker.prototype.disposeGeometry = function () {
27849 if (!this._geometry) {
27852 this._disposeGeometry();
27853 this._geometry = undefined;
27855 Marker.prototype.getInteractiveObjects = function () {
27856 if (!this._geometry) {
27859 return this._getInteractiveObjects();
27861 Marker.prototype.lerpAltitude = function (alt, alpha) {
27862 if (!this._geometry) {
27865 this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
27867 Marker.prototype.updatePosition = function (position, latLon) {
27869 this._latLon.lat = latLon.lat;
27870 this._latLon.lon = latLon.lon;
27872 if (!this._geometry) {
27875 this._geometry.position.fromArray(position);
27876 this._geometry.updateMatrixWorld(true);
27880 exports.Marker = Marker;
27881 exports.default = Marker;
27883 },{}],330:[function(require,module,exports){
27885 /// <reference path="../../../../typings/index.d.ts" />
27886 var __extends = (this && this.__extends) || (function () {
27887 var extendStatics = Object.setPrototypeOf ||
27888 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27889 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27890 return function (d, b) {
27891 extendStatics(d, b);
27892 function __() { this.constructor = d; }
27893 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27896 Object.defineProperty(exports, "__esModule", { value: true });
27897 var THREE = require("three");
27898 var Component_1 = require("../../../Component");
27900 * @class SimpleMarker
27902 * @classdesc Interactive marker with ice cream shape. The sphere
27903 * inside the ice cream can be configured to be interactive.
27905 * Simple marker properties can not be updated after creation.
27907 * To create and add one `SimpleMarker` with default configuration
27908 * (non-interactive) and one interactive with configuration use
27912 * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
27914 * { lat: 0, lon: 0, });
27916 * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
27918 * { lat: 0, lon: 0, },
27920 * ballColor: "#00f",
27921 * ballOpacity: 0.5,
27923 * interactive: true,
27928 * markerComponent.add([defaultMarker, interactiveMarker]);
27931 var SimpleMarker = /** @class */ (function (_super) {
27932 __extends(SimpleMarker, _super);
27933 function SimpleMarker(id, latLon, options) {
27934 var _this = _super.call(this, id, latLon) || this;
27935 options = !!options ? options : {};
27936 _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
27937 _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
27938 _this._circleToRayAngle = 2;
27939 _this._color = options.color != null ? options.color : 0xff0000;
27940 _this._interactive = !!options.interactive;
27941 _this._opacity = options.opacity != null ? options.opacity : 0.4;
27942 _this._radius = options.radius != null ? options.radius : 1;
27945 SimpleMarker.prototype._createGeometry = function (position) {
27946 var radius = this._radius;
27947 var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
27948 color: this._color,
27949 opacity: this._opacity,
27952 cone.renderOrder = 1;
27953 var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
27954 color: this._ballColor,
27955 opacity: this._ballOpacity,
27958 ball.position.z = this._markerHeight(radius);
27959 var group = new THREE.Object3D();
27962 group.position.fromArray(position);
27963 this._geometry = group;
27965 SimpleMarker.prototype._disposeGeometry = function () {
27966 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
27968 mesh.geometry.dispose();
27969 mesh.material.dispose();
27972 SimpleMarker.prototype._getInteractiveObjects = function () {
27973 return this._interactive ? [this._geometry.children[0]] : [];
27975 SimpleMarker.prototype._markerHeight = function (radius) {
27976 var t = Math.tan(Math.PI - this._circleToRayAngle);
27977 return radius * Math.sqrt(1 + t * t);
27979 SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
27980 var geometry = new THREE.Geometry();
27981 widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
27982 heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
27983 var height = this._markerHeight(radius);
27985 for (var y = 0; y <= heightSegments; ++y) {
27986 var verticesRow = [];
27987 for (var x = 0; x <= widthSegments; ++x) {
27988 var u = x / widthSegments * Math.PI * 2;
27989 var v = y / heightSegments * Math.PI;
27991 if (v < this._circleToRayAngle) {
27995 var t = Math.tan(v - this._circleToRayAngle);
27996 r = radius * Math.sqrt(1 + t * t);
27998 var vertex = new THREE.Vector3();
27999 vertex.x = r * Math.cos(u) * Math.sin(v);
28000 vertex.y = r * Math.sin(u) * Math.sin(v);
28001 vertex.z = r * Math.cos(v) + height;
28002 geometry.vertices.push(vertex);
28003 verticesRow.push(geometry.vertices.length - 1);
28005 vertices.push(verticesRow);
28007 for (var y = 0; y < heightSegments; ++y) {
28008 for (var x = 0; x < widthSegments; ++x) {
28009 var v1 = vertices[y][x + 1];
28010 var v2 = vertices[y][x];
28011 var v3 = vertices[y + 1][x];
28012 var v4 = vertices[y + 1][x + 1];
28013 var n1 = geometry.vertices[v1].clone().normalize();
28014 var n2 = geometry.vertices[v2].clone().normalize();
28015 var n3 = geometry.vertices[v3].clone().normalize();
28016 var n4 = geometry.vertices[v4].clone().normalize();
28017 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
28018 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
28021 geometry.computeFaceNormals();
28022 geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
28025 return SimpleMarker;
28026 }(Component_1.Marker));
28027 exports.SimpleMarker = SimpleMarker;
28028 exports.default = SimpleMarker;
28030 },{"../../../Component":281,"three":231}],331:[function(require,module,exports){
28032 /// <reference path="../../../typings/index.d.ts" />
28033 var __extends = (this && this.__extends) || (function () {
28034 var extendStatics = Object.setPrototypeOf ||
28035 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28036 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28037 return function (d, b) {
28038 extendStatics(d, b);
28039 function __() { this.constructor = d; }
28040 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28043 Object.defineProperty(exports, "__esModule", { value: true });
28044 var Observable_1 = require("rxjs/Observable");
28045 var Component_1 = require("../../Component");
28047 * The `BounceHandler` ensures that the viewer bounces back to the image
28048 * when drag panning outside of the image edge.
28050 var BounceHandler = /** @class */ (function (_super) {
28051 __extends(BounceHandler, _super);
28052 function BounceHandler(component, container, navigator, viewportCoords, spatial) {
28053 var _this = _super.call(this, component, container, navigator) || this;
28054 _this._spatial = spatial;
28055 _this._viewportCoords = viewportCoords;
28056 _this._basicDistanceThreshold = 1e-3;
28057 _this._basicRotationThreshold = 5e-2;
28058 _this._bounceCoeff = 1e-1;
28061 BounceHandler.prototype._enable = function () {
28063 var inTransition$ = this._navigator.stateService.currentState$
28064 .map(function (frame) {
28065 return frame.state.alpha < 1;
28067 this._bounceSubscription = Observable_1.Observable
28068 .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
28069 .map(function (noForce) {
28070 return noForce[0] || noForce[1] || noForce[2] || noForce[3];
28072 .distinctUntilChanged()
28073 .switchMap(function (noForce) {
28075 Observable_1.Observable.empty() :
28076 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
28078 .subscribe(function (args) {
28079 var renderCamera = args[0];
28080 var perspectiveCamera = renderCamera.perspective;
28081 var transform = args[1];
28082 if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
28085 if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
28088 var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
28089 var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
28090 if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
28093 var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
28096 if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
28097 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
28100 if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
28101 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
28104 var coeff = _this._bounceCoeff;
28105 if (basicDistances[1] > 0 && basicDistances[3] === 0) {
28106 basicX = -coeff * basicDistances[1];
28108 else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
28109 basicX = coeff * basicDistances[3];
28111 else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
28112 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
28114 if (basicDistances[0] > 0 && basicDistances[2] === 0) {
28115 basicY = coeff * basicDistances[0];
28117 else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
28118 basicY = -coeff * basicDistances[2];
28120 else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
28121 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
28123 var rotationThreshold = _this._basicRotationThreshold;
28124 basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
28125 basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
28126 _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
28129 BounceHandler.prototype._disable = function () {
28130 this._bounceSubscription.unsubscribe();
28132 BounceHandler.prototype._getConfiguration = function (enable) {
28135 return BounceHandler;
28136 }(Component_1.HandlerBase));
28137 exports.BounceHandler = BounceHandler;
28138 exports.default = BounceHandler;
28140 },{"../../Component":281,"rxjs/Observable":29}],332:[function(require,module,exports){
28142 var __extends = (this && this.__extends) || (function () {
28143 var extendStatics = Object.setPrototypeOf ||
28144 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28145 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28146 return function (d, b) {
28147 extendStatics(d, b);
28148 function __() { this.constructor = d; }
28149 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28152 Object.defineProperty(exports, "__esModule", { value: true });
28153 var Observable_1 = require("rxjs/Observable");
28154 var Component_1 = require("../../Component");
28156 * The `DoubleClickZoomHandler` allows the user to zoom the viewer image at a point by double clicking.
28160 * var mouseComponent = viewer.getComponent("mouse");
28162 * mouseComponent.doubleClickZoom.disable();
28163 * mouseComponent.doubleClickZoom.enable();
28165 * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
28168 var DoubleClickZoomHandler = /** @class */ (function (_super) {
28169 __extends(DoubleClickZoomHandler, _super);
28170 function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
28171 var _this = _super.call(this, component, container, navigator) || this;
28172 _this._viewportCoords = viewportCoords;
28175 DoubleClickZoomHandler.prototype._enable = function () {
28177 this._zoomSubscription = Observable_1.Observable
28178 .merge(this._container.mouseService
28179 .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
28180 .map(function (e) {
28181 var touch = e.touches[0];
28182 return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
28184 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
28185 .subscribe(function (_a) {
28186 var event = _a[0], render = _a[1], transform = _a[2];
28187 var element = _this._container.element;
28188 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
28189 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28190 var reference = transform.projectBasic(unprojected.toArray());
28191 var delta = !!event.shiftKey ? -1 : 1;
28192 _this._navigator.stateService.zoomIn(delta, reference);
28195 DoubleClickZoomHandler.prototype._disable = function () {
28196 this._zoomSubscription.unsubscribe();
28198 DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
28199 return { doubleClickZoom: enable };
28201 return DoubleClickZoomHandler;
28202 }(Component_1.HandlerBase));
28203 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
28204 exports.default = DoubleClickZoomHandler;
28206 },{"../../Component":281,"rxjs/Observable":29}],333:[function(require,module,exports){
28208 /// <reference path="../../../typings/index.d.ts" />
28209 var __extends = (this && this.__extends) || (function () {
28210 var extendStatics = Object.setPrototypeOf ||
28211 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28212 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28213 return function (d, b) {
28214 extendStatics(d, b);
28215 function __() { this.constructor = d; }
28216 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28219 Object.defineProperty(exports, "__esModule", { value: true });
28220 var THREE = require("three");
28221 var Observable_1 = require("rxjs/Observable");
28222 require("rxjs/add/operator/concat");
28223 require("rxjs/add/operator/sample");
28224 require("rxjs/add/operator/takeWhile");
28225 var Component_1 = require("../../Component");
28227 * The `DragPanHandler` allows the user to pan the viewer image by clicking and dragging the cursor.
28231 * var mouseComponent = viewer.getComponent("mouse");
28233 * mouseComponent.dragPan.disable();
28234 * mouseComponent.dragPan.enable();
28236 * var isEnabled = mouseComponent.dragPan.isEnabled;
28239 var DragPanHandler = /** @class */ (function (_super) {
28240 __extends(DragPanHandler, _super);
28241 function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
28242 var _this = _super.call(this, component, container, navigator) || this;
28243 _this._spatial = spatial;
28244 _this._viewportCoords = viewportCoords;
28245 _this._basicRotationThreshold = 5e-2;
28246 _this._forceCoeff = 2e-1;
28249 DragPanHandler.prototype._enable = function () {
28251 var draggingStarted$ = this._container.mouseService
28252 .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
28253 .map(function (event) {
28257 var draggingStopped$ = this._container.mouseService
28258 .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
28259 .map(function (event) {
28263 this._activeMouseSubscription = Observable_1.Observable
28264 .merge(draggingStarted$, draggingStopped$)
28265 .subscribe(this._container.mouseService.activate$);
28266 this._preventDefaultSubscription = Observable_1.Observable
28267 .merge(draggingStarted$, draggingStopped$)
28268 .switchMap(function (dragging) {
28270 _this._container.mouseService.documentMouseMove$ :
28271 Observable_1.Observable.empty();
28273 .merge(this._container.touchService.touchMove$)
28274 .subscribe(function (event) {
28275 event.preventDefault(); // prevent selection of content outside the viewer
28277 var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
28278 .map(function (event) {
28281 var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
28282 .map(function (event) {
28285 this._activeTouchSubscription = Observable_1.Observable
28286 .merge(touchMovingStarted$, touchMovingStopped$)
28287 .subscribe(this._container.touchService.activate$);
28288 var basicRotation$ = this._navigator.stateService.currentState$
28289 .map(function (frame) {
28290 return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
28292 .distinctUntilChanged()
28293 .switchMap(function (enable) {
28295 return Observable_1.Observable.empty();
28297 var mouseDrag$ = _this._container.mouseService
28298 .filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$)
28299 .switchMap(function (mouseDragStart) {
28300 return Observable_1.Observable
28301 .of(mouseDragStart)
28302 .concat(_this._container.mouseService
28303 .filtered$(_this._component.name, _this._container.mouseService.mouseDrag$))
28304 .merge(_this._container.mouseService
28305 .filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$)
28306 .map(function (e) {
28309 .takeWhile(function (e) {
28315 .filter(function (pair) {
28316 return pair[0] != null && pair[1] != null;
28318 var singleTouchDrag$ = Observable_1.Observable
28319 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
28320 .map(function (event) {
28321 return event != null && event.touches.length > 0 ?
28322 event.touches[0] : null;
28325 .filter(function (pair) {
28326 return pair[0] != null && pair[1] != null;
28328 return Observable_1.Observable
28329 .merge(mouseDrag$, singleTouchDrag$);
28331 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
28332 .map(function (_a) {
28333 var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
28334 var camera = c.clone();
28335 var previousEvent = events[0];
28336 var event = events[1];
28337 var movementX = event.clientX - previousEvent.clientX;
28338 var movementY = event.clientY - previousEvent.clientY;
28339 var element = _this._container.element;
28340 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
28341 var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
28342 .sub(render.perspective.position);
28343 var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
28344 .sub(render.perspective.position);
28345 var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
28346 .sub(render.perspective.position);
28347 var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
28348 var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
28349 var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
28350 var upQuaternionInverse = upQuaternion.clone().inverse();
28351 var offset = new THREE.Vector3();
28352 offset.copy(camera.lookat).sub(camera.position);
28353 offset.applyQuaternion(upQuaternion);
28354 var length = offset.length();
28355 var phi = Math.atan2(offset.y, offset.x);
28357 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
28358 theta += deltaTheta;
28359 theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
28360 offset.x = Math.sin(theta) * Math.cos(phi);
28361 offset.y = Math.sin(theta) * Math.sin(phi);
28362 offset.z = Math.cos(theta);
28363 offset.applyQuaternion(upQuaternionInverse);
28364 var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
28365 var basic = transform.projectBasic(lookat.toArray());
28366 var original = transform.projectBasic(camera.lookat.toArray());
28367 var x = basic[0] - original[0];
28368 var y = basic[1] - original[1];
28369 if (Math.abs(x) > 1) {
28372 else if (x > 0.5) {
28375 else if (x < -0.5) {
28378 var rotationThreshold = _this._basicRotationThreshold;
28379 x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
28380 y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
28381 if (transform.fullPano) {
28384 var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
28385 var coeff = _this._forceCoeff;
28386 if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
28387 y /= Math.max(1, coeff * pixelDistances[0]);
28389 if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
28390 x /= Math.max(1, coeff * pixelDistances[1]);
28392 if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
28393 y /= Math.max(1, coeff * pixelDistances[2]);
28395 if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
28396 x /= Math.max(1, coeff * pixelDistances[3]);
28401 this._rotateBasicWithoutInertiaSubscription = basicRotation$
28402 .subscribe(function (basicRotation) {
28403 _this._navigator.stateService.rotateBasicWithoutInertia(basicRotation);
28405 this._rotateBasicSubscription = basicRotation$
28406 .scan(function (rotationBuffer, rotation) {
28407 _this._drainBuffer(rotationBuffer);
28408 rotationBuffer.push([Date.now(), rotation]);
28409 return rotationBuffer;
28411 .sample(Observable_1.Observable
28412 .merge(this._container.mouseService.filtered$(this._component.name, this._container.mouseService.mouseDragEnd$), this._container.touchService.singleTouchDragEnd$))
28413 .map(function (rotationBuffer) {
28414 var drainedBuffer = _this._drainBuffer(rotationBuffer.slice());
28415 var basicRotation = [0, 0];
28416 for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) {
28417 var rotation = drainedBuffer_1[_i];
28418 basicRotation[0] += rotation[1][0];
28419 basicRotation[1] += rotation[1][1];
28421 var count = drainedBuffer.length;
28423 basicRotation[0] /= count;
28424 basicRotation[1] /= count;
28426 return basicRotation;
28428 .subscribe(function (basicRotation) {
28429 _this._navigator.stateService.rotateBasic(basicRotation);
28432 DragPanHandler.prototype._disable = function () {
28433 this._activeMouseSubscription.unsubscribe();
28434 this._activeTouchSubscription.unsubscribe();
28435 this._preventDefaultSubscription.unsubscribe();
28436 this._rotateBasicSubscription.unsubscribe();
28437 this._rotateBasicWithoutInertiaSubscription.unsubscribe();
28438 this._activeMouseSubscription = null;
28439 this._activeTouchSubscription = null;
28440 this._preventDefaultSubscription = null;
28441 this._rotateBasicSubscription = null;
28443 DragPanHandler.prototype._getConfiguration = function (enable) {
28444 return { dragPan: enable };
28446 DragPanHandler.prototype._drainBuffer = function (buffer) {
28448 var now = Date.now();
28449 while (buffer.length > 0 && now - buffer[0][0] > cutoff) {
28454 return DragPanHandler;
28455 }(Component_1.HandlerBase));
28456 exports.DragPanHandler = DragPanHandler;
28457 exports.default = DragPanHandler;
28459 },{"../../Component":281,"rxjs/Observable":29,"rxjs/add/operator/concat":54,"rxjs/add/operator/sample":74,"rxjs/add/operator/takeWhile":84,"three":231}],334:[function(require,module,exports){
28461 var __extends = (this && this.__extends) || (function () {
28462 var extendStatics = Object.setPrototypeOf ||
28463 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28464 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28465 return function (d, b) {
28466 extendStatics(d, b);
28467 function __() { this.constructor = d; }
28468 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28471 Object.defineProperty(exports, "__esModule", { value: true });
28472 require("rxjs/add/observable/merge");
28473 require("rxjs/add/operator/filter");
28474 require("rxjs/add/operator/map");
28475 require("rxjs/add/operator/withLatestFrom");
28476 var Component_1 = require("../../Component");
28477 var Geo_1 = require("../../Geo");
28479 * @class MouseComponent
28481 * @classdesc Component handling mouse and touch events for camera movement.
28483 * To retrive and use the mouse component
28487 * var viewer = new Mapillary.Viewer(
28492 * var mouseComponent = viewer.getComponent("mouse");
28495 var MouseComponent = /** @class */ (function (_super) {
28496 __extends(MouseComponent, _super);
28497 function MouseComponent(name, container, navigator) {
28498 var _this = _super.call(this, name, container, navigator) || this;
28499 var spatial = new Geo_1.Spatial();
28500 var viewportCoords = new Geo_1.ViewportCoords();
28501 _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
28502 _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
28503 _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
28504 _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
28505 _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
28508 Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
28510 * Get double click zoom.
28512 * @returns {DoubleClickZoomHandler} The double click zoom handler.
28515 return this._doubleClickZoomHandler;
28520 Object.defineProperty(MouseComponent.prototype, "dragPan", {
28524 * @returns {DragPanHandler} The drag pan handler.
28527 return this._dragPanHandler;
28532 Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
28536 * @returns {ScrollZoomHandler} The scroll zoom handler.
28539 return this._scrollZoomHandler;
28544 Object.defineProperty(MouseComponent.prototype, "touchZoom", {
28548 * @returns {TouchZoomHandler} The touch zoom handler.
28551 return this._touchZoomHandler;
28556 MouseComponent.prototype._activate = function () {
28558 this._bounceHandler.enable();
28559 this._configurationSubscription = this._configuration$
28560 .subscribe(function (configuration) {
28561 if (configuration.doubleClickZoom) {
28562 _this._doubleClickZoomHandler.enable();
28565 _this._doubleClickZoomHandler.disable();
28567 if (configuration.dragPan) {
28568 _this._dragPanHandler.enable();
28571 _this._dragPanHandler.disable();
28573 if (configuration.scrollZoom) {
28574 _this._scrollZoomHandler.enable();
28577 _this._scrollZoomHandler.disable();
28579 if (configuration.touchZoom) {
28580 _this._touchZoomHandler.enable();
28583 _this._touchZoomHandler.disable();
28586 this._container.mouseService.claimMouse(this._name, 0);
28588 MouseComponent.prototype._deactivate = function () {
28589 this._container.mouseService.unclaimMouse(this._name);
28590 this._configurationSubscription.unsubscribe();
28591 this._bounceHandler.disable();
28592 this._doubleClickZoomHandler.disable();
28593 this._dragPanHandler.disable();
28594 this._scrollZoomHandler.disable();
28595 this._touchZoomHandler.disable();
28597 MouseComponent.prototype._getDefaultConfiguration = function () {
28598 return { doubleClickZoom: true, dragPan: true, scrollZoom: true, touchZoom: true };
28601 MouseComponent.componentName = "mouse";
28602 return MouseComponent;
28603 }(Component_1.Component));
28604 exports.MouseComponent = MouseComponent;
28605 Component_1.ComponentService.register(MouseComponent);
28606 exports.default = MouseComponent;
28608 },{"../../Component":281,"../../Geo":284,"rxjs/add/observable/merge":44,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":87}],335:[function(require,module,exports){
28610 var __extends = (this && this.__extends) || (function () {
28611 var extendStatics = Object.setPrototypeOf ||
28612 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28613 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28614 return function (d, b) {
28615 extendStatics(d, b);
28616 function __() { this.constructor = d; }
28617 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28620 Object.defineProperty(exports, "__esModule", { value: true });
28621 var Component_1 = require("../../Component");
28623 * The `ScrollZoomHandler` allows the user to zoom the viewer image by scrolling.
28627 * var mouseComponent = viewer.getComponent("mouse");
28629 * mouseComponent.scrollZoom.disable();
28630 * mouseComponent.scrollZoom.enable();
28632 * var isEnabled = mouseComponent.scrollZoom.isEnabled;
28635 var ScrollZoomHandler = /** @class */ (function (_super) {
28636 __extends(ScrollZoomHandler, _super);
28637 function ScrollZoomHandler(component, container, navigator, viewportCoords) {
28638 var _this = _super.call(this, component, container, navigator) || this;
28639 _this._viewportCoords = viewportCoords;
28642 ScrollZoomHandler.prototype._enable = function () {
28644 this._container.mouseService.claimWheel(this._component.name, 0);
28645 this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
28646 .subscribe(function (event) {
28647 event.preventDefault();
28649 this._zoomSubscription = this._container.mouseService
28650 .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$)
28651 .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
28654 .filter(function (args) {
28655 var state = args[1].state;
28656 return state.currentNode.fullPano || state.nodesAhead < 1;
28658 .map(function (args) {
28661 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
28664 .subscribe(function (args) {
28665 var event = args[0];
28666 var render = args[1];
28667 var transform = args[2];
28668 var element = _this._container.element;
28669 var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
28670 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28671 var reference = transform.projectBasic(unprojected.toArray());
28672 var deltaY = event.deltaY;
28673 if (event.deltaMode === 1) {
28674 deltaY = 40 * deltaY;
28676 else if (event.deltaMode === 2) {
28677 deltaY = 800 * deltaY;
28679 var canvasSize = _this._viewportCoords.containerToCanvas(element);
28680 var zoom = -3 * deltaY / canvasSize[1];
28681 _this._navigator.stateService.zoomIn(zoom, reference);
28684 ScrollZoomHandler.prototype._disable = function () {
28685 this._container.mouseService.unclaimWheel(this._component.name);
28686 this._preventDefaultSubscription.unsubscribe();
28687 this._zoomSubscription.unsubscribe();
28688 this._preventDefaultSubscription = null;
28689 this._zoomSubscription = null;
28691 ScrollZoomHandler.prototype._getConfiguration = function (enable) {
28692 return { scrollZoom: enable };
28694 return ScrollZoomHandler;
28695 }(Component_1.HandlerBase));
28696 exports.ScrollZoomHandler = ScrollZoomHandler;
28697 exports.default = ScrollZoomHandler;
28699 },{"../../Component":281}],336:[function(require,module,exports){
28701 /// <reference path="../../../typings/index.d.ts" />
28702 var __extends = (this && this.__extends) || (function () {
28703 var extendStatics = Object.setPrototypeOf ||
28704 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28705 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28706 return function (d, b) {
28707 extendStatics(d, b);
28708 function __() { this.constructor = d; }
28709 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28712 Object.defineProperty(exports, "__esModule", { value: true });
28713 var Observable_1 = require("rxjs/Observable");
28714 var Component_1 = require("../../Component");
28716 * The `TouchZoomHandler` allows the user to zoom the viewer image by pinching on a touchscreen.
28720 * var mouseComponent = viewer.getComponent("mouse");
28722 * mouseComponent.touchZoom.disable();
28723 * mouseComponent.touchZoom.enable();
28725 * var isEnabled = mouseComponent.touchZoom.isEnabled;
28728 var TouchZoomHandler = /** @class */ (function (_super) {
28729 __extends(TouchZoomHandler, _super);
28730 function TouchZoomHandler(component, container, navigator, viewportCoords) {
28731 var _this = _super.call(this, component, container, navigator) || this;
28732 _this._viewportCoords = viewportCoords;
28735 TouchZoomHandler.prototype._enable = function () {
28737 this._preventDefaultSubscription = this._container.touchService.pinch$
28738 .subscribe(function (pinch) {
28739 pinch.originalEvent.preventDefault();
28741 var pinchStarted$ = this._container.touchService.pinchStart$
28742 .map(function (event) {
28745 var pinchStopped$ = this._container.touchService.pinchEnd$
28746 .map(function (event) {
28749 this._activeSubscription = Observable_1.Observable
28750 .merge(pinchStarted$, pinchStopped$)
28751 .subscribe(this._container.touchService.activate$);
28752 this._zoomSubscription = this._container.touchService.pinch$
28753 .withLatestFrom(this._navigator.stateService.currentState$)
28754 .filter(function (args) {
28755 var state = args[1].state;
28756 return state.currentNode.fullPano || state.nodesAhead < 1;
28758 .map(function (args) {
28761 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
28762 .subscribe(function (_a) {
28763 var pinch = _a[0], render = _a[1], transform = _a[2];
28764 var element = _this._container.element;
28765 var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
28766 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28767 var reference = transform.projectBasic(unprojected.toArray());
28768 var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
28769 var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
28770 _this._navigator.stateService.zoomIn(zoom, reference);
28773 TouchZoomHandler.prototype._disable = function () {
28774 this._activeSubscription.unsubscribe();
28775 this._preventDefaultSubscription.unsubscribe();
28776 this._zoomSubscription.unsubscribe();
28777 this._preventDefaultSubscription = null;
28778 this._zoomSubscription = null;
28780 TouchZoomHandler.prototype._getConfiguration = function (enable) {
28781 return { touchZoom: enable };
28783 return TouchZoomHandler;
28784 }(Component_1.HandlerBase));
28785 exports.TouchZoomHandler = TouchZoomHandler;
28786 exports.default = TouchZoomHandler;
28788 },{"../../Component":281,"rxjs/Observable":29}],337:[function(require,module,exports){
28790 Object.defineProperty(exports, "__esModule", { value: true });
28791 var Popup_1 = require("./popup/Popup");
28792 exports.Popup = Popup_1.Popup;
28793 var PopupComponent_1 = require("./PopupComponent");
28794 exports.PopupComponent = PopupComponent_1.PopupComponent;
28796 },{"./PopupComponent":338,"./popup/Popup":339}],338:[function(require,module,exports){
28798 var __extends = (this && this.__extends) || (function () {
28799 var extendStatics = Object.setPrototypeOf ||
28800 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28801 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28802 return function (d, b) {
28803 extendStatics(d, b);
28804 function __() { this.constructor = d; }
28805 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28808 Object.defineProperty(exports, "__esModule", { value: true });
28809 var Observable_1 = require("rxjs/Observable");
28810 var Subject_1 = require("rxjs/Subject");
28811 var Component_1 = require("../../Component");
28812 var Utils_1 = require("../../Utils");
28814 * @class PopupComponent
28816 * @classdesc Component for showing HTML popup objects.
28818 * The `add` method is used for adding new popups. Popups are removed by reference.
28820 * It is not possible to update popups in the set by updating any properties
28821 * directly on the popup object. Popups need to be replaced by
28822 * removing them and creating new ones with relevant changed properties and
28823 * adding those instead.
28825 * Popups are only relevant to a single image because they are based on
28826 * 2D basic image coordinates. Popups related to a certain image should
28827 * be removed when the viewer is moved to another node.
28829 * To retrive and use the popup component
28833 * var viewer = new Mapillary.Viewer(
28837 * { component: { popup: true } });
28839 * var popupComponent = viewer.getComponent("popup");
28842 var PopupComponent = /** @class */ (function (_super) {
28843 __extends(PopupComponent, _super);
28844 function PopupComponent(name, container, navigator, dom) {
28845 var _this = _super.call(this, name, container, navigator) || this;
28846 _this._dom = !!dom ? dom : new Utils_1.DOM();
28847 _this._popups = [];
28848 _this._added$ = new Subject_1.Subject();
28849 _this._popups$ = new Subject_1.Subject();
28853 * Add popups to the popups set.
28855 * @description Adding a new popup never replaces an old one
28856 * because they are stored by reference. Adding an already
28857 * existing popup has no effect.
28859 * @param {Array<Popup>} popups - Popups to add.
28861 * @example ```popupComponent.add([popup1, popup2]);```
28863 PopupComponent.prototype.add = function (popups) {
28864 for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
28865 var popup = popups_1[_i];
28866 if (this._popups.indexOf(popup) !== -1) {
28869 this._popups.push(popup);
28870 if (this._activated) {
28871 popup.setParentContainer(this._popupContainer);
28874 this._added$.next(popups);
28875 this._popups$.next(this._popups);
28878 * Returns an array of all popups.
28880 * @example ```var popups = popupComponent.getAll();```
28882 PopupComponent.prototype.getAll = function () {
28883 return this._popups.slice();
28886 * Remove popups based on reference from the popup set.
28888 * @param {Array<Popup>} popups - Popups to remove.
28890 * @example ```popupComponent.remove([popup1, popup2]);```
28892 PopupComponent.prototype.remove = function (popups) {
28893 for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
28894 var popup = popups_2[_i];
28895 this._remove(popup);
28897 this._popups$.next(this._popups);
28900 * Remove all popups from the popup set.
28902 * @example ```popupComponent.removeAll();```
28904 PopupComponent.prototype.removeAll = function () {
28905 for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
28906 var popup = _a[_i];
28907 this._remove(popup);
28909 this._popups$.next(this._popups);
28911 PopupComponent.prototype._activate = function () {
28913 this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element);
28914 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
28915 var popup = _a[_i];
28916 popup.setParentContainer(this._popupContainer);
28918 this._updateAllSubscription = Observable_1.Observable
28919 .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
28920 .subscribe(function (_a) {
28921 var renderCamera = _a[0], size = _a[1], transform = _a[2];
28922 for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
28923 var popup = _b[_i];
28924 popup.update(renderCamera, size, transform);
28927 var changed$ = this._popups$
28928 .startWith(this._popups)
28929 .switchMap(function (popups) {
28930 return Observable_1.Observable
28932 .mergeMap(function (popup) {
28933 return popup.changed$;
28936 .map(function (popup) {
28939 this._updateAddedChangedSubscription = this._added$
28941 .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
28942 .subscribe(function (_a) {
28943 var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
28944 for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
28945 var popup = popups_3[_i];
28946 popup.update(renderCamera, size, transform);
28950 PopupComponent.prototype._deactivate = function () {
28951 this._updateAllSubscription.unsubscribe();
28952 this._updateAddedChangedSubscription.unsubscribe();
28953 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
28954 var popup = _a[_i];
28957 this._container.element.removeChild(this._popupContainer);
28958 delete this._popupContainer;
28960 PopupComponent.prototype._getDefaultConfiguration = function () {
28963 PopupComponent.prototype._remove = function (popup) {
28964 var index = this._popups.indexOf(popup);
28965 if (index === -1) {
28968 var removed = this._popups.splice(index, 1)[0];
28969 if (this._activated) {
28973 PopupComponent.componentName = "popup";
28974 return PopupComponent;
28975 }(Component_1.Component));
28976 exports.PopupComponent = PopupComponent;
28977 Component_1.ComponentService.register(PopupComponent);
28978 exports.default = PopupComponent;
28980 },{"../../Component":281,"../../Utils":291,"rxjs/Observable":29,"rxjs/Subject":34}],339:[function(require,module,exports){
28982 /// <reference path="../../../../typings/index.d.ts" />
28983 Object.defineProperty(exports, "__esModule", { value: true });
28984 var Subject_1 = require("rxjs/Subject");
28985 var Geo_1 = require("../../../Geo");
28986 var Utils_1 = require("../../../Utils");
28987 var Viewer_1 = require("../../../Viewer");
28991 * @classdesc Popup instance for rendering custom HTML content
28992 * on top of images. Popups are based on 2D basic image coordinates
28993 * (see the {@link Viewer} class documentation for more information about coordinate
28994 * systems) and a certain popup is therefore only relevant to a single image.
28995 * Popups related to a certain image should be removed when moving
28996 * to another image.
28998 * A popup must have both its content and its point or rect set to be
28999 * rendered. Popup options can not be updated after creation but the
29000 * basic point or rect as well as its content can be changed by calling
29001 * the appropriate methods.
29003 * To create and add one `Popup` with default configuration
29004 * (tooltip visuals and automatic float) and one with specific options
29009 * var defaultSpan = document.createElement('span');
29010 * defaultSpan.innerHTML = 'hello default';
29012 * var defaultPopup = new Mapillary.PopupComponent.Popup();
29013 * defaultPopup.setDOMContent(defaultSpan);
29014 * defaultPopup.setBasicPoint([0.3, 0.3]);
29016 * var cleanSpan = document.createElement('span');
29017 * cleanSpan.innerHTML = 'hello clean';
29019 * var cleanPopup = new Mapillary.PopupComponent.Popup({
29021 * float: Mapillary.Alignment.Top,
29026 * cleanPopup.setDOMContent(cleanSpan);
29027 * cleanPopup.setBasicPoint([0.6, 0.6]);
29029 * popupComponent.add([defaultPopup, cleanPopup]);
29032 * @description Implementation of API methods and API documentation inspired
29033 * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
29035 var Popup = /** @class */ (function () {
29036 function Popup(options, viewportCoords, dom) {
29037 this._options = {};
29039 this._options.capturePointer = options.capturePointer == null ? true : options.capturePointer;
29040 this._options.clean = options.clean;
29041 this._options.float = options.float;
29042 this._options.offset = options.offset;
29043 this._options.opacity = options.opacity;
29044 this._options.position = options.position;
29046 this._dom = !!dom ? dom : new Utils_1.DOM();
29047 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
29048 this._notifyChanged$ = new Subject_1.Subject();
29050 Object.defineProperty(Popup.prototype, "changed$", {
29054 * @description Internal observable used by the component to
29055 * render the popup when its position or content has changed.
29058 return this._notifyChanged$;
29066 * @description Internal method used by the component to
29067 * remove all references to the popup.
29069 Popup.prototype.remove = function () {
29070 if (this._content && this._content.parentNode) {
29071 this._content.parentNode.removeChild(this._content);
29073 if (this._container) {
29074 this._container.parentNode.removeChild(this._container);
29075 delete this._container;
29077 if (this._parentContainer) {
29078 delete this._parentContainer;
29082 * Sets a 2D basic image coordinates point to the popup's anchor, and
29083 * moves the popup to it.
29085 * @description Overwrites any previously set point or rect.
29087 * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
29091 * var popup = new Mapillary.PopupComponent.Popup();
29092 * popup.setText('hello image');
29093 * popup.setBasicPoint([0.3, 0.3]);
29095 * popupComponent.add([popup]);
29098 Popup.prototype.setBasicPoint = function (basicPoint) {
29099 this._point = basicPoint.slice();
29101 this._notifyChanged$.next(this);
29104 * Sets a 2D basic image coordinates rect to the popup's anchor, and
29105 * moves the popup to it.
29107 * @description Overwrites any previously set point or rect.
29109 * @param {Array<number>} basicRect - Rect in 2D basic image
29110 * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
29114 * var popup = new Mapillary.PopupComponent.Popup();
29115 * popup.setText('hello image');
29116 * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
29118 * popupComponent.add([popup]);
29121 Popup.prototype.setBasicRect = function (basicRect) {
29122 this._rect = basicRect.slice();
29123 this._point = null;
29124 this._notifyChanged$.next(this);
29127 * Sets the popup's content to the element provided as a DOM node.
29129 * @param {Node} htmlNode - A DOM node to be used as content for the popup.
29133 * var div = document.createElement('div');
29134 * div.innerHTML = 'hello image';
29136 * var popup = new Mapillary.PopupComponent.Popup();
29137 * popup.setDOMContent(div);
29138 * popup.setBasicPoint([0.3, 0.3]);
29140 * popupComponent.add([popup]);
29143 Popup.prototype.setDOMContent = function (htmlNode) {
29144 if (this._content && this._content.parentNode) {
29145 this._content.parentNode.removeChild(this._content);
29147 var className = "mapillaryjs-popup-content" +
29148 (this._options.clean === true ? "-clean" : "") +
29149 (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
29150 this._content = this._dom.createElement("div", className, this._container);
29151 this._content.appendChild(htmlNode);
29152 this._notifyChanged$.next(this);
29155 * Sets the popup's content to the HTML provided as a string.
29157 * @description This method does not perform HTML filtering or sanitization,
29158 * and must be used only with trusted content. Consider Popup#setText if the
29159 * content is an untrusted text string.
29161 * @param {string} html - A string representing HTML content for the popup.
29165 * var popup = new Mapillary.PopupComponent.Popup();
29166 * popup.setHTML('<div>hello image</div>');
29167 * popup.setBasicPoint([0.3, 0.3]);
29169 * popupComponent.add([popup]);
29172 Popup.prototype.setHTML = function (html) {
29173 var frag = this._dom.document.createDocumentFragment();
29174 var temp = this._dom.createElement("body");
29176 temp.innerHTML = html;
29178 child = temp.firstChild;
29182 frag.appendChild(child);
29184 this.setDOMContent(frag);
29187 * Sets the popup's content to a string of text.
29189 * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
29190 * Use this method for security against XSS if the popup content is user-provided.
29192 * @param {string} text - Textual content for the popup.
29196 * var popup = new Mapillary.PopupComponent.Popup();
29197 * popup.setText('hello image');
29198 * popup.setBasicPoint([0.3, 0.3]);
29200 * popupComponent.add([popup]);
29203 Popup.prototype.setText = function (text) {
29204 this.setDOMContent(this._dom.document.createTextNode(text));
29209 * @description Internal method for attaching the popup to
29210 * its parent container so that it is rendered in the DOM tree.
29212 Popup.prototype.setParentContainer = function (parentContainer) {
29213 this._parentContainer = parentContainer;
29218 * @description Internal method for updating the rendered
29219 * position of the popup called by the popup component.
29221 Popup.prototype.update = function (renderCamera, size, transform) {
29222 if (!this._parentContainer || !this._content) {
29225 if (!this._point && !this._rect) {
29228 if (!this._container) {
29229 this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer);
29230 var showTip = this._options.clean !== true &&
29231 this._options.float !== Viewer_1.Alignment.Center;
29233 var tipClassName = "mapillaryjs-popup-tip" +
29234 (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
29235 this._tip = this._dom.createElement("div", tipClassName, this._container);
29236 this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
29238 this._container.appendChild(this._content);
29239 this._parentContainer.appendChild(this._container);
29240 if (this._options.opacity != null) {
29241 this._container.style.opacity = this._options.opacity.toString();
29244 var pointPixel = null;
29245 var position = this._alignmentToPopupAligment(this._options.position);
29246 var float = this._alignmentToPopupAligment(this._options.float);
29247 var classList = this._container.classList;
29248 if (this._point != null) {
29250 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
29253 var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
29254 var appliedPosition = null;
29255 for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) {
29256 var alignment = alignments_1[_i];
29257 if (classList.contains("mapillaryjs-popup-float-" + alignment)) {
29258 appliedPosition = alignment;
29262 _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
29267 if (pointPixel == null) {
29268 this._container.style.visibility = "hidden";
29271 this._container.style.visibility = "visible";
29273 var width = this._container.offsetWidth;
29274 var height = this._container.offsetHeight;
29275 var floats = this._pixelToFloats(pointPixel, size, width, height);
29276 float = floats.length === 0 ? "top" : floats.join("-");
29278 var offset = this._normalizeOffset(this._options.offset);
29279 pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]];
29280 pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
29281 var floatTranslate = {
29282 "bottom": "translate(-50%,0)",
29283 "bottom-left": "translate(-100%,0)",
29284 "bottom-right": "translate(0,0)",
29285 "center": "translate(-50%,-50%)",
29286 "left": "translate(-100%,-50%)",
29287 "right": "translate(0,-50%)",
29288 "top": "translate(-50%,-100%)",
29289 "top-left": "translate(-100%,-100%)",
29290 "top-right": "translate(0,-100%)",
29292 for (var key in floatTranslate) {
29293 if (!floatTranslate.hasOwnProperty(key)) {
29296 classList.remove("mapillaryjs-popup-float-" + key);
29298 classList.add("mapillaryjs-popup-float-" + float);
29299 this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
29302 Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) {
29304 var width = this._container.offsetWidth;
29305 var height = this._container.offsetHeight;
29306 var floatOffsets = {
29307 "bottom": [0, height / 2],
29308 "bottom-left": [-width / 2, height / 2],
29309 "bottom-right": [width / 2, height / 2],
29310 "left": [-width / 2, 0],
29311 "right": [width / 2, 0],
29312 "top": [0, -height / 2],
29313 "top-left": [-width / 2, -height / 2],
29314 "top-right": [width / 2, -height / 2],
29316 var automaticPositions = ["top", "bottom", "left", "right"];
29317 var largestVisibleArea = [0, null, null];
29318 for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
29319 var automaticPosition = automaticPositions_1[_i];
29320 var autoPointBasic = this._pointFromRectPosition(rect, automaticPosition);
29321 var autoPointPixel = this._viewportCoords.basicToCanvasSafe(autoPointBasic[0], autoPointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
29322 if (autoPointPixel == null) {
29325 var floatOffset = floatOffsets[automaticPosition];
29326 var offsetedPosition = [autoPointPixel[0] + floatOffset[0], autoPointPixel[1] + floatOffset[1]];
29327 var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7;
29328 var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff));
29329 if (floats.length === 0 &&
29330 autoPointPixel[0] > 0 &&
29331 autoPointPixel[0] < size.width &&
29332 autoPointPixel[1] > 0 &&
29333 autoPointPixel[1] < size.height) {
29334 return [autoPointPixel, automaticPosition];
29336 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
29337 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
29338 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
29339 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
29340 var visibleX = Math.max(0, maxX - minX);
29341 var visibleY = Math.max(0, maxY - minY);
29342 var visibleArea = staticCoeff * visibleX * visibleY;
29343 if (visibleArea > largestVisibleArea[0]) {
29344 largestVisibleArea[0] = visibleArea;
29345 largestVisibleArea[1] = autoPointPixel;
29346 largestVisibleArea[2] = automaticPosition;
29349 if (largestVisibleArea[0] > 0) {
29350 return [largestVisibleArea[1], largestVisibleArea[2]];
29353 var pointBasic = this._pointFromRectPosition(rect, position);
29354 var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
29355 return [pointPixel, position != null ? position : "top"];
29357 Popup.prototype._alignmentToPopupAligment = function (float) {
29359 case Viewer_1.Alignment.Bottom:
29361 case Viewer_1.Alignment.BottomLeft:
29362 return "bottom-left";
29363 case Viewer_1.Alignment.BottomRight:
29364 return "bottom-right";
29365 case Viewer_1.Alignment.Center:
29367 case Viewer_1.Alignment.Left:
29369 case Viewer_1.Alignment.Right:
29371 case Viewer_1.Alignment.Top:
29373 case Viewer_1.Alignment.TopLeft:
29375 case Viewer_1.Alignment.TopRight:
29376 return "top-right";
29381 Popup.prototype._normalizeOffset = function (offset) {
29382 if (offset == null) {
29383 return this._normalizeOffset(0);
29385 if (typeof offset === "number") {
29386 // input specifies a radius
29387 var sideOffset = offset;
29388 var sign = sideOffset >= 0 ? 1 : -1;
29389 var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2)));
29391 "bottom": [0, sideOffset],
29392 "bottom-left": [-cornerOffset, cornerOffset],
29393 "bottom-right": [cornerOffset, cornerOffset],
29395 "left": [-sideOffset, 0],
29396 "right": [sideOffset, 0],
29397 "top": [0, -sideOffset],
29398 "top-left": [-cornerOffset, -cornerOffset],
29399 "top-right": [cornerOffset, -cornerOffset],
29403 // input specifes a value for each position
29405 "bottom": offset.bottom || [0, 0],
29406 "bottom-left": offset.bottomLeft || [0, 0],
29407 "bottom-right": offset.bottomRight || [0, 0],
29408 "center": offset.center || [0, 0],
29409 "left": offset.left || [0, 0],
29410 "right": offset.right || [0, 0],
29411 "top": offset.top || [0, 0],
29412 "top-left": offset.topLeft || [0, 0],
29413 "top-right": offset.topRight || [0, 0],
29417 Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
29419 if (pointPixel[1] < height) {
29420 floats.push("bottom");
29422 else if (pointPixel[1] > size.height - height) {
29423 floats.push("top");
29425 if (pointPixel[0] < width / 2) {
29426 floats.push("right");
29428 else if (pointPixel[0] > size.width - width / 2) {
29429 floats.push("left");
29433 Popup.prototype._pointFromRectPosition = function (rect, position) {
29435 var x1 = rect[0] < rect[2] ? rect[2] : rect[2] + 1;
29438 switch (position) {
29440 return [(x0 + x1) / 2, y1];
29441 case "bottom-left":
29443 case "bottom-right":
29446 return [(x0 + x1) / 2, (y0 + y1) / 2];
29448 return [x0, (y0 + y1) / 2];
29450 return [x1, (y0 + y1) / 2];
29452 return [(x0 + x1) / 2, y0];
29458 return [(x0 + x1) / 2, y1];
29463 exports.Popup = Popup;
29464 exports.default = Popup;
29466 },{"../../../Geo":284,"../../../Utils":291,"../../../Viewer":292,"rxjs/Subject":34}],340:[function(require,module,exports){
29468 Object.defineProperty(exports, "__esModule", { value: true });
29470 (function (ControlMode) {
29471 ControlMode[ControlMode["Default"] = 0] = "Default";
29472 ControlMode[ControlMode["Playback"] = 1] = "Playback";
29473 })(ControlMode = exports.ControlMode || (exports.ControlMode = {}));
29474 exports.default = ControlMode;
29476 },{}],341:[function(require,module,exports){
29478 /// <reference path="../../../typings/index.d.ts" />
29479 var __extends = (this && this.__extends) || (function () {
29480 var extendStatics = Object.setPrototypeOf ||
29481 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29482 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29483 return function (d, b) {
29484 extendStatics(d, b);
29485 function __() { this.constructor = d; }
29486 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29489 Object.defineProperty(exports, "__esModule", { value: true });
29490 var Observable_1 = require("rxjs/Observable");
29491 var Subject_1 = require("rxjs/Subject");
29492 require("rxjs/add/observable/combineLatest");
29493 require("rxjs/add/observable/of");
29494 require("rxjs/add/operator/bufferCount");
29495 require("rxjs/add/operator/concat");
29496 require("rxjs/add/operator/distinctUntilChanged");
29497 require("rxjs/add/operator/filter");
29498 require("rxjs/add/operator/finally");
29499 require("rxjs/add/operator/first");
29500 require("rxjs/add/operator/map");
29501 require("rxjs/add/operator/publishReplay");
29502 require("rxjs/add/operator/retry");
29503 require("rxjs/add/operator/scan");
29504 require("rxjs/add/operator/share");
29505 require("rxjs/add/operator/switchMap");
29506 require("rxjs/add/operator/takeUntil");
29507 require("rxjs/add/operator/withLatestFrom");
29508 var Component_1 = require("../../Component");
29509 var Edge_1 = require("../../Edge");
29511 * @class SequenceComponent
29512 * @classdesc Component showing navigation arrows for sequence directions
29513 * as well as playing button. Exposes an API to start and stop play.
29515 var SequenceComponent = /** @class */ (function (_super) {
29516 __extends(SequenceComponent, _super);
29517 function SequenceComponent(name, container, navigator) {
29518 var _this = _super.call(this, name, container, navigator) || this;
29519 _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container);
29520 _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
29521 _this._containerWidth$ = new Subject_1.Subject();
29522 _this._hoveredKeySubject$ = new Subject_1.Subject();
29523 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
29524 _this._navigator.playService.playing$
29526 .withLatestFrom(_this._configuration$)
29527 .subscribe(function (_a) {
29528 var playing = _a[0], configuration = _a[1];
29529 _this.fire(SequenceComponent.playingchanged, playing);
29530 if (playing === configuration.playing) {
29540 _this._navigator.playService.direction$
29542 .withLatestFrom(_this._configuration$)
29543 .subscribe(function (_a) {
29544 var direction = _a[0], configuration = _a[1];
29545 if (direction !== configuration.direction) {
29546 _this.setDirection(direction);
29551 Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
29553 * Get hovered key observable.
29555 * @description An observable emitting the key of the node for the direction
29556 * arrow that is being hovered. When the mouse leaves a direction arrow null
29559 * @returns {Observable<string>}
29562 return this._hoveredKey$;
29570 * @fires PlayerComponent#playingchanged
29572 SequenceComponent.prototype.play = function () {
29573 this.configure({ playing: true });
29578 * @fires PlayerComponent#playingchanged
29580 SequenceComponent.prototype.stop = function () {
29581 this.configure({ playing: false });
29584 * Set the direction to follow when playing.
29586 * @param {EdgeDirection} direction - The direction that will be followed when playing.
29588 SequenceComponent.prototype.setDirection = function (direction) {
29589 this.configure({ direction: direction });
29592 * Set highlight key.
29594 * @description The arrow pointing towards the node corresponding to the
29595 * highlight key will be highlighted.
29597 * @param {string} highlightKey Key of node to be highlighted if existing.
29599 SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
29600 this.configure({ highlightKey: highlightKey });
29603 * Set max width of container element.
29605 * @description Set max width of the container element holding
29606 * the sequence navigation elements. If the min width is larger than the
29607 * max width the min width value will be used.
29609 * The container element is automatically resized when the resize
29610 * method on the Viewer class is called.
29612 * @param {number} minWidth
29614 SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
29615 this.configure({ maxWidth: maxWidth });
29618 * Set min width of container element.
29620 * @description Set min width of the container element holding
29621 * the sequence navigation elements. If the min width is larger than the
29622 * max width the min width value will be used.
29624 * The container element is automatically resized when the resize
29625 * method on the Viewer class is called.
29627 * @param {number} minWidth
29629 SequenceComponent.prototype.setMinWidth = function (minWidth) {
29630 this.configure({ minWidth: minWidth });
29633 * Set the value indicating whether the sequence UI elements should be visible.
29635 * @param {boolean} visible
29637 SequenceComponent.prototype.setVisible = function (visible) {
29638 this.configure({ visible: visible });
29641 SequenceComponent.prototype.resize = function () {
29643 this._configuration$
29645 .map(function (configuration) {
29646 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
29648 .subscribe(function (containerWidth) {
29649 _this._containerWidth$.next(containerWidth);
29652 SequenceComponent.prototype._activate = function () {
29654 this._sequenceDOMRenderer.activate();
29655 var edgeStatus$ = this._navigator.stateService.currentNode$
29656 .switchMap(function (node) {
29657 return node.sequenceEdges$;
29661 this._renderSubscription = Observable_1.Observable
29662 .combineLatest(edgeStatus$, this._configuration$, this._containerWidth$, this._sequenceDOMRenderer.changed$.startWith(this._sequenceDOMRenderer), this._navigator.playService.speed$)
29663 .map(function (_a) {
29664 var edgeStatus = _a[0], configuration = _a[1], containerWidth = _a[2], renderer = _a[3], speed = _a[4];
29665 var vNode = _this._sequenceDOMRenderer
29666 .render(edgeStatus, configuration, containerWidth, speed, _this, _this._sequenceDOMInteraction, _this._navigator);
29667 return { name: _this._name, vnode: vNode };
29669 .subscribe(this._container.domRenderer.render$);
29670 this._setSpeedSubscription = this._sequenceDOMRenderer.speed$
29671 .subscribe(function (speed) {
29672 _this._navigator.playService.setSpeed(speed);
29674 this._setDirectionSubscription = this._configuration$
29675 .map(function (configuration) {
29676 return configuration.direction;
29678 .distinctUntilChanged()
29679 .subscribe(function (direction) {
29680 _this._navigator.playService.setDirection(direction);
29682 this._containerWidthSubscription = this._configuration$
29683 .distinctUntilChanged(function (value1, value2) {
29684 return value1[0] === value2[0] && value1[1] === value2[1];
29685 }, function (configuration) {
29686 return [configuration.minWidth, configuration.maxWidth];
29688 .map(function (configuration) {
29689 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
29691 .subscribe(this._containerWidth$);
29692 this._playingSubscription = this._configuration$
29693 .map(function (configuration) {
29694 return configuration.playing;
29696 .distinctUntilChanged()
29697 .subscribe(function (playing) {
29699 _this._navigator.playService.play();
29702 _this._navigator.playService.stop();
29705 this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
29706 .switchMap(function (direction) {
29708 .map(function (edgeStatus) {
29709 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
29711 if (edge.data.direction === direction) {
29717 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
29718 .concat(Observable_1.Observable.of(null));
29720 .distinctUntilChanged()
29721 .subscribe(this._hoveredKeySubject$);
29723 SequenceComponent.prototype._deactivate = function () {
29724 this._renderSubscription.unsubscribe();
29725 this._playingSubscription.unsubscribe();
29726 this._containerWidthSubscription.unsubscribe();
29727 this._hoveredKeySubscription.unsubscribe();
29728 this._setSpeedSubscription.unsubscribe();
29729 this._setDirectionSubscription.unsubscribe();
29730 this._sequenceDOMRenderer.deactivate();
29732 SequenceComponent.prototype._getDefaultConfiguration = function () {
29734 direction: Edge_1.EdgeDirection.Next,
29742 SequenceComponent.componentName = "sequence";
29744 * Event fired when playing starts or stops.
29746 * @event PlayerComponent#playingchanged
29747 * @type {boolean} Indicates whether the player is playing.
29749 SequenceComponent.playingchanged = "playingchanged";
29750 return SequenceComponent;
29751 }(Component_1.Component));
29752 exports.SequenceComponent = SequenceComponent;
29753 Component_1.ComponentService.register(SequenceComponent);
29754 exports.default = SequenceComponent;
29756 },{"../../Component":281,"../../Edge":282,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/of":45,"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/concat":54,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/retry":73,"rxjs/add/operator/scan":75,"rxjs/add/operator/share":76,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/takeUntil":83,"rxjs/add/operator/withLatestFrom":87}],342:[function(require,module,exports){
29758 Object.defineProperty(exports, "__esModule", { value: true });
29759 var Subject_1 = require("rxjs/Subject");
29760 var SequenceDOMInteraction = /** @class */ (function () {
29761 function SequenceDOMInteraction() {
29762 this._mouseEnterDirection$ = new Subject_1.Subject();
29763 this._mouseLeaveDirection$ = new Subject_1.Subject();
29765 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
29767 return this._mouseEnterDirection$;
29772 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
29774 return this._mouseLeaveDirection$;
29779 return SequenceDOMInteraction;
29781 exports.SequenceDOMInteraction = SequenceDOMInteraction;
29782 exports.default = SequenceDOMInteraction;
29784 },{"rxjs/Subject":34}],343:[function(require,module,exports){
29786 /// <reference path="../../../typings/index.d.ts" />
29787 Object.defineProperty(exports, "__esModule", { value: true });
29788 var vd = require("virtual-dom");
29789 var Observable_1 = require("rxjs/Observable");
29790 var Subject_1 = require("rxjs/Subject");
29791 var Component_1 = require("../../Component");
29792 var Edge_1 = require("../../Edge");
29793 var SequenceDOMRenderer = /** @class */ (function () {
29794 function SequenceDOMRenderer(container) {
29795 this._container = container;
29796 this._minThresholdWidth = 320;
29797 this._maxThresholdWidth = 1480;
29798 this._minThresholdHeight = 240;
29799 this._maxThresholdHeight = 820;
29800 this._stepperDefaultWidth = 108;
29801 this._controlsDefaultWidth = 52;
29802 this._defaultHeight = 30;
29803 this._expandControls = false;
29804 this._mode = Component_1.ControlMode.Default;
29806 this._changingSpeed = false;
29807 this._notifyChanged$ = new Subject_1.Subject();
29808 this._notifySpeedChanged$ = new Subject_1.Subject();
29810 Object.defineProperty(SequenceDOMRenderer.prototype, "speed", {
29812 return this._speed;
29817 Object.defineProperty(SequenceDOMRenderer.prototype, "changed$", {
29819 return this._notifyChanged$;
29824 Object.defineProperty(SequenceDOMRenderer.prototype, "speed$", {
29826 return this._notifySpeedChanged$;
29831 SequenceDOMRenderer.prototype.activate = function () {
29833 if (!!this._changingSpeedSubscription) {
29836 this._changingSpeedSubscription = Observable_1.Observable
29837 .merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$
29838 .filter(function (touchEvent) {
29839 return touchEvent.touches.length === 0;
29841 .subscribe(function (event) {
29842 if (_this._changingSpeed) {
29843 _this._changingSpeed = false;
29847 SequenceDOMRenderer.prototype.deactivate = function () {
29848 if (!this._changingSpeedSubscription) {
29851 this._changingSpeed = false;
29852 this._expandControls = false;
29853 this._mode = Component_1.ControlMode.Default;
29854 this._changingSpeedSubscription.unsubscribe();
29855 this._changingSpeedSubscription = null;
29857 SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, speed, component, interaction, navigator) {
29858 if (configuration.visible === false) {
29859 return vd.h("div.SequenceContainer", {}, []);
29861 var stepper = this._createStepper(edgeStatus, configuration, containerWidth, component, interaction, navigator);
29862 var controls = this._createSequenceControls(containerWidth);
29863 var playback = this._createPlaybackControls(containerWidth, speed, component, configuration);
29864 return vd.h("div.SequenceContainer", [stepper, controls, playback]);
29866 SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
29867 var elementWidth = element.offsetWidth;
29868 var elementHeight = element.offsetHeight;
29869 var minWidth = configuration.minWidth;
29870 var maxWidth = configuration.maxWidth;
29871 if (maxWidth < minWidth) {
29872 maxWidth = minWidth;
29874 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
29875 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
29876 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
29877 return minWidth + coeff * (maxWidth - minWidth);
29879 SequenceDOMRenderer.prototype._createSpeedInput = function (speed) {
29881 this._speed = speed;
29882 var onSpeed = function (e) {
29883 _this._speed = Number(e.target.value) / 1000;
29884 _this._notifySpeedChanged$.next(_this._speed);
29886 var boundingRect = this._container.domContainer.getBoundingClientRect();
29887 var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 160;
29888 var onStart = function (e) {
29889 _this._changingSpeed = true;
29890 e.stopPropagation();
29892 var onMove = function (e) {
29893 if (_this._changingSpeed === true) {
29894 e.stopPropagation();
29897 var speedInput = vd.h("input.SequenceSpeed", {
29902 onmousedown: onStart,
29903 onmousemove: onMove,
29904 ontouchmove: onMove,
29905 ontouchstart: onStart,
29907 width: width + "px",
29910 value: 1000 * speed,
29912 return vd.h("div.SequenceSpeedContainer", [speedInput]);
29914 SequenceDOMRenderer.prototype._createPlaybackControls = function (containerWidth, speed, component, configuration) {
29916 if (this._mode !== Component_1.ControlMode.Playback) {
29917 return vd.h("div.SequencePlayback", []);
29919 var switchIcon = vd.h("div.SequenceSwitchIcon.SequenceIconVisible", []);
29920 var direction = configuration.direction === Edge_1.EdgeDirection.Next ?
29921 Edge_1.EdgeDirection.Prev : Edge_1.EdgeDirection.Next;
29922 var playing = configuration.playing;
29923 var switchButtonProperties = {
29924 onclick: function () {
29926 component.setDirection(direction);
29930 var switchButtonClassName = configuration.playing ? ".SequenceSwitchButtonDisabled" : ".SequenceSwitchButton";
29931 var switchButton = vd.h("div" + switchButtonClassName, switchButtonProperties, [switchIcon]);
29932 var slowIcon = vd.h("div.SequenceSlowIcon.SequenceIconVisible", []);
29933 var slowContainer = vd.h("div.SequenceSlowContainer", [slowIcon]);
29934 var fastIcon = vd.h("div.SequenceFastIconGrey.SequenceIconVisible", []);
29935 var fastContainer = vd.h("div.SequenceFastContainer", [fastIcon]);
29936 var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
29937 var closeButtonProperties = {
29938 onclick: function () {
29939 _this._mode = Component_1.ControlMode.Default;
29940 _this._notifyChanged$.next(_this);
29943 var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
29944 var speedInput = this._createSpeedInput(speed);
29945 var playbackChildren = [switchButton, slowContainer, speedInput, fastContainer, closeButton];
29946 var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
29947 var playbackProperties = { style: { top: top + "px" } };
29948 return vd.h("div.SequencePlayback", playbackProperties, playbackChildren);
29950 SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
29951 var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
29952 configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
29953 var onclick = configuration.playing ?
29954 function (e) { component.stop(); } :
29955 canPlay ? function (e) { component.play(); } : null;
29956 var buttonProperties = { onclick: onclick };
29957 var iconClass = configuration.playing ?
29959 canPlay ? "Play" : "PlayDisabled";
29960 var iconProperties = { className: iconClass };
29961 if (configuration.direction === Edge_1.EdgeDirection.Prev) {
29962 iconProperties.style = {
29963 transform: "rotate(180deg) translate(50%, 50%)",
29966 var icon = vd.h("div.SequenceComponentIcon", iconProperties, []);
29967 var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
29968 return vd.h("div." + buttonClass, buttonProperties, [icon]);
29970 SequenceDOMRenderer.prototype._createSequenceControls = function (containerWidth) {
29972 var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
29973 var expanderProperties = {
29974 onclick: function () {
29975 _this._expandControls = !_this._expandControls;
29976 _this._mode = Component_1.ControlMode.Default;
29977 _this._notifyChanged$.next(_this);
29980 "border-bottom-right-radius": borderRadius + "px",
29981 "border-top-right-radius": borderRadius + "px",
29984 var expanderBar = vd.h("div.SequenceExpanderBar", []);
29985 var expander = vd.h("div.SequenceExpanderButton", expanderProperties, [expanderBar]);
29986 var fastIconClassName = this._mode === Component_1.ControlMode.Playback ?
29987 ".SequenceFastIconGrey.SequenceIconVisible" : ".SequenceFastIcon";
29988 var fastIcon = vd.h("div" + fastIconClassName, []);
29989 var playbackProperties = {
29990 onclick: function () {
29991 _this._mode = _this._mode === Component_1.ControlMode.Playback ?
29992 Component_1.ControlMode.Default :
29993 Component_1.ControlMode.Playback;
29994 _this._notifyChanged$.next(_this);
29997 var controls = vd.h("div.SequencePlaybackButton", playbackProperties, [fastIcon]);
30000 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
30001 transform: "translate(" + (containerWidth / 2 + 2) + "px, 0)",
30002 width: (this._controlsDefaultWidth / this._stepperDefaultWidth * containerWidth) + "px",
30005 var className = ".SequenceControls" +
30006 (this._expandControls ? ".SequenceControlsExpanded" : "");
30007 return vd.h("div" + className, properties, [controls, expander]);
30009 SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, containerWidth, configuration, interaction, navigator) {
30010 var nextProperties = {
30011 onclick: nextKey != null ?
30013 navigator.moveDir$(Edge_1.EdgeDirection.Next)
30014 .subscribe(function (node) { return; }, function (error) { console.error(error); });
30017 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
30018 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
30020 var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
30021 var prevProperties = {
30022 onclick: prevKey != null ?
30024 navigator.moveDir$(Edge_1.EdgeDirection.Prev)
30025 .subscribe(function (node) { return; }, function (error) { console.error(error); });
30028 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
30029 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
30031 "border-bottom-left-radius": borderRadius + "px",
30032 "border-top-left-radius": borderRadius + "px",
30035 var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
30036 var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
30037 var nextIcon = vd.h("div.SequenceComponentIcon", []);
30038 var prevIcon = vd.h("div.SequenceComponentIcon", []);
30040 vd.h("div." + prevClass, prevProperties, [prevIcon]),
30041 vd.h("div." + nextClass, nextProperties, [nextIcon]),
30044 SequenceDOMRenderer.prototype._createStepper = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
30045 var nextKey = null;
30046 var prevKey = null;
30047 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
30049 if (edge.data.direction === Edge_1.EdgeDirection.Next) {
30052 if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
30056 var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
30057 var buttons = this._createSequenceArrows(nextKey, prevKey, containerWidth, configuration, interaction, navigator);
30058 buttons.splice(1, 0, playingButton);
30059 var containerProperties = {
30060 oncontextmenu: function (event) { event.preventDefault(); },
30062 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
30063 width: containerWidth + "px",
30066 return vd.h("div.SequenceStepper", containerProperties, buttons);
30068 SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
30069 var className = direction === Edge_1.EdgeDirection.Next ?
30070 "SequenceStepNext" :
30071 "SequenceStepPrev";
30073 className += "Disabled";
30076 if (highlightKey === key) {
30077 className += "Highlight";
30082 return SequenceDOMRenderer;
30084 exports.SequenceDOMRenderer = SequenceDOMRenderer;
30085 exports.default = SequenceDOMRenderer;
30087 },{"../../Component":281,"../../Edge":282,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":237}],344:[function(require,module,exports){
30089 Object.defineProperty(exports, "__esModule", { value: true });
30090 var GeometryTagError_1 = require("./error/GeometryTagError");
30091 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
30092 var PointGeometry_1 = require("./geometry/PointGeometry");
30093 exports.PointGeometry = PointGeometry_1.PointGeometry;
30094 var RectGeometry_1 = require("./geometry/RectGeometry");
30095 exports.RectGeometry = RectGeometry_1.RectGeometry;
30096 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
30097 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
30098 var OutlineTag_1 = require("./tag/OutlineTag");
30099 exports.OutlineTag = OutlineTag_1.OutlineTag;
30100 var SpotTag_1 = require("./tag/SpotTag");
30101 exports.SpotTag = SpotTag_1.SpotTag;
30102 var TagComponent_1 = require("./TagComponent");
30103 exports.TagComponent = TagComponent_1.TagComponent;
30104 var TagMode_1 = require("./TagMode");
30105 exports.TagMode = TagMode_1.TagMode;
30107 },{"./TagComponent":345,"./TagMode":348,"./error/GeometryTagError":352,"./geometry/PointGeometry":354,"./geometry/PolygonGeometry":355,"./geometry/RectGeometry":356,"./tag/OutlineTag":368,"./tag/SpotTag":371}],345:[function(require,module,exports){
30109 /// <reference path="../../../typings/index.d.ts" />
30110 var __extends = (this && this.__extends) || (function () {
30111 var extendStatics = Object.setPrototypeOf ||
30112 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30113 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30114 return function (d, b) {
30115 extendStatics(d, b);
30116 function __() { this.constructor = d; }
30117 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30120 Object.defineProperty(exports, "__esModule", { value: true });
30121 var when = require("when");
30122 var Observable_1 = require("rxjs/Observable");
30123 require("rxjs/add/observable/combineLatest");
30124 require("rxjs/add/observable/empty");
30125 require("rxjs/add/observable/from");
30126 require("rxjs/add/observable/merge");
30127 require("rxjs/add/observable/of");
30128 require("rxjs/add/operator/combineLatest");
30129 require("rxjs/add/operator/concat");
30130 require("rxjs/add/operator/distinctUntilChanged");
30131 require("rxjs/add/operator/do");
30132 require("rxjs/add/operator/filter");
30133 require("rxjs/add/operator/map");
30134 require("rxjs/add/operator/merge");
30135 require("rxjs/add/operator/mergeMap");
30136 require("rxjs/add/operator/publishReplay");
30137 require("rxjs/add/operator/scan");
30138 require("rxjs/add/operator/share");
30139 require("rxjs/add/operator/skip");
30140 require("rxjs/add/operator/skipUntil");
30141 require("rxjs/add/operator/startWith");
30142 require("rxjs/add/operator/switchMap");
30143 require("rxjs/add/operator/take");
30144 require("rxjs/add/operator/takeUntil");
30145 require("rxjs/add/operator/withLatestFrom");
30146 var Component_1 = require("../../Component");
30147 var Geo_1 = require("../../Geo");
30148 var Render_1 = require("../../Render");
30150 * @class TagComponent
30152 * @classdesc Component for showing and editing tags with different
30153 * geometries composed from 2D basic image coordinates (see the
30154 * {@link Viewer} class documentation for more information about coordinate
30157 * The `add` method is used for adding new tags or replacing
30158 * tags already in the set. Tags are removed by id.
30160 * If a tag already in the set has the same
30161 * id as one of the tags added, the old tag will be removed and
30162 * the added tag will take its place.
30164 * The tag component mode can be set to either be non interactive or
30165 * to be in creating mode of a certain geometry type.
30167 * The tag properties can be updated at any time and the change will
30168 * be visibile immediately.
30170 * Tags are only relevant to a single image because they are based on
30171 * 2D basic image coordinates. Tags related to a certain image should
30172 * be removed when the viewer is moved to another node.
30174 * To retrive and use the tag component
30178 * var viewer = new Mapillary.Viewer(
30182 * { component: { tag: true } });
30184 * var tagComponent = viewer.getComponent("tag");
30187 var TagComponent = /** @class */ (function (_super) {
30188 __extends(TagComponent, _super);
30189 function TagComponent(name, container, navigator) {
30190 var _this = _super.call(this, name, container, navigator) || this;
30191 _this._tagDomRenderer = new Component_1.TagDOMRenderer();
30192 _this._tagScene = new Component_1.TagScene();
30193 _this._tagSet = new Component_1.TagSet();
30194 _this._tagCreator = new Component_1.TagCreator(_this, navigator);
30195 _this._viewportCoords = new Geo_1.ViewportCoords();
30196 _this._createHandlers = {
30197 "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
30198 "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
30199 "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
30200 "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
30201 "Default": undefined,
30203 _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet);
30204 _this._renderTags$ = _this._tagSet.changed$
30205 .map(function (tagSet) {
30206 var tags = tagSet.getAll();
30207 // ensure that tags are always rendered in the same order
30208 // to avoid hover tracking problems on first resize.
30209 tags.sort(function (t1, t2) {
30210 var id1 = t1.tag.id;
30211 var id2 = t2.tag.id;
30223 _this._tagChanged$ = _this._renderTags$
30224 .switchMap(function (tags) {
30225 return Observable_1.Observable
30227 .mergeMap(function (tag) {
30228 return Observable_1.Observable
30229 .merge(tag.tag.changed$, tag.tag.geometryChanged$);
30233 _this._renderTagGLChanged$ = _this._renderTags$
30234 .switchMap(function (tags) {
30235 return Observable_1.Observable
30237 .mergeMap(function (tag) {
30238 return tag.glObjectsChanged$;
30242 _this._createGeometryChanged$ = _this._tagCreator.tag$
30243 .switchMap(function (tag) {
30244 return tag != null ?
30245 tag.geometryChanged$ :
30246 Observable_1.Observable.empty();
30249 _this._createGLObjectsChanged$ = _this._tagCreator.tag$
30250 .switchMap(function (tag) {
30251 return tag != null ?
30252 tag.glObjectsChanged$ :
30253 Observable_1.Observable.empty();
30256 _this._creatingConfiguration$ = _this._configuration$
30257 .distinctUntilChanged(function (c1, c2) {
30258 return c1.mode === c2.mode;
30259 }, function (configuration) {
30261 createColor: configuration.createColor,
30262 mode: configuration.mode,
30267 _this._creatingConfiguration$
30268 .subscribe(function (configuration) {
30269 _this.fire(TagComponent.modechanged, configuration.mode);
30274 * Add tags to the tag set or replace tags in the tag set.
30276 * @description If a tag already in the set has the same
30277 * id as one of the tags added, the old tag will be removed
30278 * the added tag will take its place.
30280 * @param {Array<Tag>} tags - Tags to add.
30282 * @example ```tagComponent.add([tag1, tag2]);```
30284 TagComponent.prototype.add = function (tags) {
30286 if (this._activated) {
30287 this._navigator.stateService.currentTransform$
30289 .subscribe(function (transform) {
30290 _this._tagSet.add(tags, transform);
30291 var renderTags = tags
30292 .map(function (tag) {
30293 return _this._tagSet.get(tag.id);
30295 _this._tagScene.add(renderTags);
30299 this._tagSet.addDeactivated(tags);
30303 * Change the current tag mode.
30305 * @description Change the tag mode to one of the create modes for creating new geometries.
30307 * @param {TagMode} mode - New tag mode.
30309 * @fires TagComponent#modechanged
30311 * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
30313 TagComponent.prototype.changeMode = function (mode) {
30314 this.configure({ mode: mode });
30317 * Returns the tag in the tag set with the specified id, or
30318 * undefined if the id matches no tag.
30320 * @param {string} tagId - Id of the tag.
30322 * @example ```var tag = tagComponent.get("tagId");```
30324 TagComponent.prototype.get = function (tagId) {
30325 if (this._activated) {
30326 var renderTag = this._tagSet.get(tagId);
30327 return renderTag !== undefined ? renderTag.tag : undefined;
30330 return this._tagSet.getDeactivated(tagId);
30334 * Returns an array of all tags.
30336 * @example ```var tags = tagComponent.getAll();```
30338 TagComponent.prototype.getAll = function () {
30339 if (this.activated) {
30340 return this._tagSet
30342 .map(function (renderTag) {
30343 return renderTag.tag;
30347 return this._tagSet.getAllDeactivated();
30351 * Returns an array of tag ids for tags that contain the specified point.
30353 * @description The pixel point must lie inside the polygon or rectangle
30354 * of an added tag for the tag id to be returned. Tag ids for
30355 * tags that do not have a fill will also be returned if the point is inside
30356 * the geometry of the tag. Tags with point geometries can not be retrieved.
30358 * No tag ids will be returned for panoramas.
30360 * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
30362 * With this function, you can use the coordinates provided by mouse
30363 * events to get information out of the tag component.
30365 * If no tag at exist the pixel point, an empty array will be returned.
30367 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
30368 * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
30372 * tagComponent.getTagIdsAt([100, 100])
30373 * .then((tagIds) => { console.log(tagIds); });
30376 TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
30378 return when.promise(function (resolve, reject) {
30379 _this._container.renderService.renderCamera$
30381 .map(function (render) {
30382 var viewport = _this._viewportCoords
30383 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
30384 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
30387 .subscribe(function (ids) {
30389 }, function (error) {
30395 * Check if a tag exist in the tag set.
30397 * @param {string} tagId - Id of the tag.
30399 * @example ```var tagExists = tagComponent.has("tagId");```
30401 TagComponent.prototype.has = function (tagId) {
30402 return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
30405 * Remove tags with the specified ids from the tag set.
30407 * @param {Array<string>} tagIds - Ids for tags to remove.
30409 * @example ```tagComponent.remove(["id-1", "id-2"]);```
30411 TagComponent.prototype.remove = function (tagIds) {
30412 if (this._activated) {
30413 this._tagSet.remove(tagIds);
30414 this._tagScene.remove(tagIds);
30417 this._tagSet.removeDeactivated(tagIds);
30421 * Remove all tags from the tag set.
30423 * @example ```tagComponent.removeAll();```
30425 TagComponent.prototype.removeAll = function () {
30426 if (this._activated) {
30427 this._tagSet.removeAll();
30428 this._tagScene.removeAll();
30431 this._tagSet.removeAllDeactivated();
30434 TagComponent.prototype._activate = function () {
30436 this._editVertexHandler.enable();
30437 var handlerGeometryCreated$ = Observable_1.Observable
30438 .from(Object.keys(this._createHandlers))
30439 .map(function (key) {
30440 return _this._createHandlers[key];
30442 .filter(function (handler) {
30445 .mergeMap(function (handler) {
30446 return handler.geometryCreated$;
30449 this._fireGeometryCreatedSubscription = handlerGeometryCreated$
30450 .subscribe(function (geometry) {
30451 _this.fire(TagComponent.geometrycreated, geometry);
30453 this._fireCreateGeometryEventSubscription = this._tagCreator.tag$
30454 .skipWhile(function (tag) {
30455 return tag == null;
30457 .distinctUntilChanged()
30458 .subscribe(function (tag) {
30459 var eventType = tag != null ?
30460 TagComponent.creategeometrystart :
30461 TagComponent.creategeometryend;
30462 _this.fire(eventType, _this);
30464 this._handlerStopCreateSubscription = handlerGeometryCreated$
30465 .subscribe(function () {
30466 _this.changeMode(Component_1.TagMode.Default);
30468 this._handlerEnablerSubscription = this._creatingConfiguration$
30469 .subscribe(function (configuration) {
30470 _this._disableCreateHandlers();
30471 var mode = Component_1.TagMode[configuration.mode];
30472 var handler = _this._createHandlers[mode];
30477 this._fireTagsChangedSubscription = this._renderTags$
30478 .subscribe(function (tags) {
30479 _this.fire(TagComponent.tagschanged, _this);
30481 this._stopCreateSubscription = this._tagCreator.tag$
30482 .switchMap(function (tag) {
30483 return tag != null ?
30485 .map(function (t) { return null; }) :
30486 Observable_1.Observable.empty();
30488 .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
30489 this._setGLCreateTagSubscription = this._tagCreator.tag$
30490 .subscribe(function (tag) {
30491 if (_this._tagScene.hasCreateTag()) {
30492 _this._tagScene.removeCreateTag();
30495 _this._tagScene.addCreateTag(tag);
30498 this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
30499 .subscribe(function (tag) {
30500 _this._tagScene.updateCreateTagObjects(tag);
30502 this._updateGLObjectsSubscription = this._renderTagGLChanged$
30503 .subscribe(function (tag) {
30504 _this._tagScene.updateObjects(tag);
30506 this._updateTagSceneSubscription = this._tagChanged$
30507 .subscribe(function (tag) {
30508 _this._tagScene.update();
30510 this._domSubscription = this._renderTags$
30512 .do(function (tags) {
30513 _this._container.domRenderer.render$.next({
30515 vnode: _this._tagDomRenderer.clear(),
30518 .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) {
30519 return [rc, atlas, size, renderTags, tag, ct];
30521 .map(function (args) {
30524 vnode: _this._tagDomRenderer.render(args[3], args[5], args[1], args[0].perspective, args[2]),
30527 .subscribe(this._container.domRenderer.render$);
30528 this._glSubscription = this._navigator.stateService.currentState$
30529 .map(function (frame) {
30530 var tagScene = _this._tagScene;
30535 needsRender: tagScene.needsRender,
30536 render: tagScene.render.bind(tagScene),
30537 stage: Render_1.GLRenderStage.Foreground,
30541 .subscribe(this._container.glRenderer.render$);
30542 this._navigator.stateService.currentTransform$
30544 .subscribe(function (transform) {
30545 _this._tagSet.activate(transform);
30546 _this._tagScene.add(_this._tagSet.getAll());
30549 TagComponent.prototype._deactivate = function () {
30550 this._editVertexHandler.disable();
30551 this._disableCreateHandlers();
30552 this._tagScene.clear();
30553 this._tagSet.deactivate();
30554 this._tagCreator.delete$.next(null);
30555 this._updateGLObjectsSubscription.unsubscribe();
30556 this._updateTagSceneSubscription.unsubscribe();
30557 this._stopCreateSubscription.unsubscribe();
30558 this._setGLCreateTagSubscription.unsubscribe();
30559 this._createGLObjectsChangedSubscription.unsubscribe();
30560 this._domSubscription.unsubscribe();
30561 this._glSubscription.unsubscribe();
30562 this._fireCreateGeometryEventSubscription.unsubscribe();
30563 this._fireGeometryCreatedSubscription.unsubscribe();
30564 this._fireTagsChangedSubscription.unsubscribe();
30565 this._handlerStopCreateSubscription.unsubscribe();
30566 this._handlerEnablerSubscription.unsubscribe();
30567 this._container.element.classList.remove("component-tag-create");
30569 TagComponent.prototype._getDefaultConfiguration = function () {
30571 createColor: 0xFFFFFF,
30572 mode: Component_1.TagMode.Default,
30575 TagComponent.prototype._disableCreateHandlers = function () {
30576 var createHandlers = this._createHandlers;
30577 for (var key in createHandlers) {
30578 if (!createHandlers.hasOwnProperty(key)) {
30581 var handler = createHandlers[key];
30588 TagComponent.componentName = "tag";
30590 * Event fired when an interaction to create a geometry ends.
30592 * @description A create interaction can by a geometry being created
30593 * or by the creation being aborted.
30595 * @event TagComponent#creategeometryend
30596 * @type {TagComponent} Tag component.
30599 * tagComponent.on("creategeometryend", function(component) {
30600 * console.log(component);
30604 TagComponent.creategeometryend = "creategeometryend";
30606 * Event fired when an interaction to create a geometry starts.
30608 * @description A create interaction starts when the first vertex
30609 * is created in the geometry.
30611 * @event TagComponent#creategeometrystart
30612 * @type {TagComponent} Tag component.
30615 * tagComponent.on("creategeometrystart", function(component) {
30616 * console.log(component);
30620 TagComponent.creategeometrystart = "creategeometrystart";
30622 * Event fired when the create mode is changed.
30624 * @event TagComponent#modechanged
30625 * @type {TagMode} Tag mode
30628 * tagComponent.on("modechanged", function(mode) {
30629 * console.log(mode);
30633 TagComponent.modechanged = "modechanged";
30635 * Event fired when a geometry has been created.
30637 * @event TagComponent#geometrycreated
30638 * @type {Geometry} Created geometry.
30641 * tagComponent.on("geometrycreated", function(geometry) {
30642 * console.log(geometry);
30646 TagComponent.geometrycreated = "geometrycreated";
30648 * Event fired when the tags collection has changed.
30650 * @event TagComponent#tagschanged
30651 * @type {TagComponent} Tag component.
30654 * tagComponent.on("tagschanged", function(component) {
30655 * console.log(component.getAll());
30659 TagComponent.tagschanged = "tagschanged";
30660 return TagComponent;
30661 }(Component_1.Component));
30662 exports.TagComponent = TagComponent;
30663 Component_1.ComponentService.register(TagComponent);
30664 exports.default = TagComponent;
30666 },{"../../Component":281,"../../Geo":284,"../../Render":287,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/empty":40,"rxjs/add/observable/from":41,"rxjs/add/observable/merge":44,"rxjs/add/observable/of":45,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/concat":54,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/share":76,"rxjs/add/operator/skip":77,"rxjs/add/operator/skipUntil":78,"rxjs/add/operator/startWith":80,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/take":82,"rxjs/add/operator/takeUntil":83,"rxjs/add/operator/withLatestFrom":87,"when":278}],346:[function(require,module,exports){
30668 Object.defineProperty(exports, "__esModule", { value: true });
30669 var Subject_1 = require("rxjs/Subject");
30670 require("rxjs/add/operator/map");
30671 require("rxjs/add/operator/scan");
30672 require("rxjs/add/operator/share");
30673 require("rxjs/add/operator/withLatestFrom");
30674 var Component_1 = require("../../Component");
30675 var TagCreator = /** @class */ (function () {
30676 function TagCreator(component, navigator) {
30677 this._component = component;
30678 this._navigator = navigator;
30679 this._tagOperation$ = new Subject_1.Subject();
30680 this._createPolygon$ = new Subject_1.Subject();
30681 this._createRect$ = new Subject_1.Subject();
30682 this._delete$ = new Subject_1.Subject();
30683 this._tag$ = this._tagOperation$
30684 .scan(function (tag, operation) {
30685 return operation(tag);
30689 .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
30690 .map(function (_a) {
30691 var coord = _a[0], conf = _a[1], transform = _a[2];
30692 return function (tag) {
30693 var geometry = new Component_1.RectGeometry([
30699 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
30702 .subscribe(this._tagOperation$);
30703 this._createPolygon$
30704 .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
30705 .map(function (_a) {
30706 var coord = _a[0], conf = _a[1], transform = _a[2];
30707 return function (tag) {
30708 var geometry = new Component_1.PolygonGeometry([
30709 [coord[0], coord[1]],
30710 [coord[0], coord[1]],
30711 [coord[0], coord[1]],
30713 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
30716 .subscribe(this._tagOperation$);
30719 return function (tag) {
30723 .subscribe(this._tagOperation$);
30725 Object.defineProperty(TagCreator.prototype, "createRect$", {
30727 return this._createRect$;
30732 Object.defineProperty(TagCreator.prototype, "createPolygon$", {
30734 return this._createPolygon$;
30739 Object.defineProperty(TagCreator.prototype, "delete$", {
30741 return this._delete$;
30746 Object.defineProperty(TagCreator.prototype, "tag$", {
30755 exports.TagCreator = TagCreator;
30756 exports.default = TagCreator;
30758 },{"../../Component":281,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":75,"rxjs/add/operator/share":76,"rxjs/add/operator/withLatestFrom":87}],347:[function(require,module,exports){
30760 /// <reference path="../../../typings/index.d.ts" />
30761 Object.defineProperty(exports, "__esModule", { value: true });
30762 var vd = require("virtual-dom");
30763 var TagDOMRenderer = /** @class */ (function () {
30764 function TagDOMRenderer() {
30766 TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
30768 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
30769 var tag = tags_1[_i];
30770 vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
30772 if (createTag != null) {
30773 vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
30775 return vd.h("div.TagContainer", {}, vNodes);
30777 TagDOMRenderer.prototype.clear = function () {
30778 return vd.h("div", {}, []);
30780 return TagDOMRenderer;
30782 exports.TagDOMRenderer = TagDOMRenderer;
30784 },{"virtual-dom":237}],348:[function(require,module,exports){
30786 Object.defineProperty(exports, "__esModule", { value: true });
30788 * Enumeration for tag modes
30791 * @description Modes for the interaction in the tag component.
30794 (function (TagMode) {
30796 * Disables creating tags.
30798 TagMode[TagMode["Default"] = 0] = "Default";
30800 * Create a point geometry through a click.
30802 TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
30804 * Create a polygon geometry through clicks.
30806 TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
30808 * Create a rect geometry through clicks.
30810 TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
30812 * Create a rect geometry through drag.
30814 * @description Claims the mouse which results in mouse handlers like
30815 * drag pan and scroll zoom becoming inactive.
30817 TagMode[TagMode["CreateRectDrag"] = 4] = "CreateRectDrag";
30818 })(TagMode = exports.TagMode || (exports.TagMode = {}));
30819 exports.default = TagMode;
30821 },{}],349:[function(require,module,exports){
30823 Object.defineProperty(exports, "__esModule", { value: true });
30825 (function (TagOperation) {
30826 TagOperation[TagOperation["None"] = 0] = "None";
30827 TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
30828 TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
30829 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
30830 exports.default = TagOperation;
30832 },{}],350:[function(require,module,exports){
30834 /// <reference path="../../../typings/index.d.ts" />
30835 Object.defineProperty(exports, "__esModule", { value: true });
30836 var THREE = require("three");
30837 var TagScene = /** @class */ (function () {
30838 function TagScene(scene, raycaster) {
30839 this._createTag = null;
30840 this._needsRender = false;
30841 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
30842 this._scene = !!scene ? scene : new THREE.Scene();
30843 this._objectTags = {};
30844 this._retrievableObjects = [];
30847 Object.defineProperty(TagScene.prototype, "needsRender", {
30849 return this._needsRender;
30854 TagScene.prototype.add = function (tags) {
30855 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
30856 var tag = tags_1[_i];
30857 if (tag.tag.id in this._tags) {
30858 this._remove(tag.tag.id);
30862 this._needsRender = true;
30864 TagScene.prototype.addCreateTag = function (tag) {
30865 for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
30866 var object = _a[_i];
30867 this._scene.add(object);
30869 this._createTag = { tag: tag, objects: tag.glObjects };
30870 this._needsRender = true;
30872 TagScene.prototype.clear = function () {
30873 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
30877 this._needsRender = false;
30879 TagScene.prototype.get = function (id) {
30880 return this.has(id) ? this._tags[id].tag : undefined;
30882 TagScene.prototype.has = function (id) {
30883 return id in this._tags;
30885 TagScene.prototype.hasCreateTag = function () {
30886 return this._createTag != null;
30888 TagScene.prototype.intersectObjects = function (_a, camera) {
30889 var viewportX = _a[0], viewportY = _a[1];
30890 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
30891 var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
30892 var intersectedIds = [];
30893 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
30894 var intersect = intersects_1[_i];
30895 if (intersect.object.uuid in this._objectTags) {
30896 intersectedIds.push(this._objectTags[intersect.object.uuid]);
30899 return intersectedIds;
30901 TagScene.prototype.remove = function (ids) {
30902 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
30903 var id = ids_1[_i];
30906 this._needsRender = true;
30908 TagScene.prototype.removeAll = function () {
30909 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
30913 this._needsRender = true;
30915 TagScene.prototype.removeCreateTag = function () {
30916 if (this._createTag == null) {
30919 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
30920 var object = _a[_i];
30921 this._scene.remove(object);
30923 this._createTag.tag.dispose();
30924 this._createTag = null;
30925 this._needsRender = true;
30927 TagScene.prototype.render = function (perspectiveCamera, renderer) {
30928 renderer.render(this._scene, perspectiveCamera);
30929 this._needsRender = false;
30931 TagScene.prototype.update = function () {
30932 this._needsRender = true;
30934 TagScene.prototype.updateCreateTagObjects = function (tag) {
30935 if (this._createTag.tag !== tag) {
30936 throw new Error("Create tags do not have the same reference.");
30938 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
30939 var object = _a[_i];
30940 this._scene.remove(object);
30942 for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
30943 var object = _c[_b];
30944 this._scene.add(object);
30946 this._createTag.objects = tag.glObjects;
30947 this._needsRender = true;
30949 TagScene.prototype.updateObjects = function (tag) {
30950 var id = tag.tag.id;
30951 if (this._tags[id].tag !== tag) {
30952 throw new Error("Tags do not have the same reference.");
30954 var tagObjects = this._tags[id];
30955 this._removeObjects(tagObjects);
30956 delete this._tags[id];
30958 this._needsRender = true;
30960 TagScene.prototype._add = function (tag) {
30961 var id = tag.tag.id;
30962 var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
30963 this._tags[id] = tagObjects;
30964 for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
30965 var object = _a[_i];
30966 tagObjects.objects.push(object);
30967 this._scene.add(object);
30969 for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
30970 var retrievableObject = _c[_b];
30971 tagObjects.retrievableObjects.push(retrievableObject);
30972 this._retrievableObjects.push(retrievableObject);
30973 this._objectTags[retrievableObject.uuid] = tag.tag.id;
30976 TagScene.prototype._remove = function (id) {
30977 var tagObjects = this._tags[id];
30978 this._removeObjects(tagObjects);
30979 tagObjects.tag.dispose();
30980 delete this._tags[id];
30982 TagScene.prototype._removeObjects = function (tagObjects) {
30983 for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
30984 var object = _a[_i];
30985 this._scene.remove(object);
30987 for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
30988 var retrievableObject = _c[_b];
30989 var index = this._retrievableObjects.indexOf(retrievableObject);
30990 if (index !== -1) {
30991 this._retrievableObjects.splice(index, 1);
30997 exports.TagScene = TagScene;
30998 exports.default = TagScene;
31000 },{"three":231}],351:[function(require,module,exports){
31002 Object.defineProperty(exports, "__esModule", { value: true });
31003 var Subject_1 = require("rxjs/Subject");
31004 require("rxjs/add/operator/map");
31005 require("rxjs/add/operator/scan");
31006 require("rxjs/add/operator/share");
31007 var Component_1 = require("../../Component");
31008 var TagSet = /** @class */ (function () {
31009 function TagSet() {
31010 this._active = false;
31012 this._hashDeactivated = {};
31013 this._notifyChanged$ = new Subject_1.Subject();
31015 Object.defineProperty(TagSet.prototype, "active", {
31017 return this._active;
31022 Object.defineProperty(TagSet.prototype, "changed$", {
31024 return this._notifyChanged$;
31029 TagSet.prototype.activate = function (transform) {
31030 if (this._active) {
31033 for (var id in this._hashDeactivated) {
31034 if (!this._hashDeactivated.hasOwnProperty(id)) {
31037 var tag = this._hashDeactivated[id];
31038 this._add(tag, transform);
31040 this._hashDeactivated = {};
31041 this._active = true;
31042 this._notifyChanged$.next(this);
31044 TagSet.prototype.deactivate = function () {
31045 if (!this._active) {
31048 for (var id in this._hash) {
31049 if (!this._hash.hasOwnProperty(id)) {
31052 this._hashDeactivated[id] = this._hash[id].tag;
31055 this._active = false;
31057 TagSet.prototype.add = function (tags, transform) {
31058 this._assertActivationState(true);
31059 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
31060 var tag = tags_1[_i];
31061 this._add(tag, transform);
31063 this._notifyChanged$.next(this);
31065 TagSet.prototype.addDeactivated = function (tags) {
31066 this._assertActivationState(false);
31067 for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
31068 var tag = tags_2[_i];
31069 if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
31070 throw new Error("Tag type not supported");
31072 this._hashDeactivated[tag.id] = tag;
31075 TagSet.prototype.get = function (id) {
31076 return this.has(id) ? this._hash[id] : undefined;
31078 TagSet.prototype.getAll = function () {
31079 var hash = this._hash;
31080 return Object.keys(hash)
31081 .map(function (id) {
31085 TagSet.prototype.getAllDeactivated = function () {
31086 var hashDeactivated = this._hashDeactivated;
31087 return Object.keys(hashDeactivated)
31088 .map(function (id) {
31089 return hashDeactivated[id];
31092 TagSet.prototype.getDeactivated = function (id) {
31093 return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
31095 TagSet.prototype.has = function (id) {
31096 return id in this._hash;
31098 TagSet.prototype.hasDeactivated = function (id) {
31099 return id in this._hashDeactivated;
31101 TagSet.prototype.remove = function (ids) {
31102 this._assertActivationState(true);
31103 var hash = this._hash;
31104 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
31105 var id = ids_1[_i];
31106 if (!(id in hash)) {
31111 this._notifyChanged$.next(this);
31113 TagSet.prototype.removeAll = function () {
31114 this._assertActivationState(true);
31116 this._notifyChanged$.next(this);
31118 TagSet.prototype.removeAllDeactivated = function () {
31119 this._assertActivationState(false);
31120 this._hashDeactivated = {};
31122 TagSet.prototype.removeDeactivated = function (ids) {
31123 this._assertActivationState(false);
31124 var hashDeactivated = this._hashDeactivated;
31125 for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
31126 var id = ids_2[_i];
31127 if (!(id in hashDeactivated)) {
31130 delete hashDeactivated[id];
31133 TagSet.prototype._add = function (tag, transform) {
31134 if (tag instanceof Component_1.OutlineTag) {
31135 this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
31137 else if (tag instanceof Component_1.SpotTag) {
31138 this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
31141 throw new Error("Tag type not supported");
31144 TagSet.prototype._assertActivationState = function (should) {
31145 if (should !== this._active) {
31146 throw new Error("Tag set not in correct state for operation.");
31151 exports.TagSet = TagSet;
31152 exports.default = TagSet;
31154 },{"../../Component":281,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":75,"rxjs/add/operator/share":76}],352:[function(require,module,exports){
31156 var __extends = (this && this.__extends) || (function () {
31157 var extendStatics = Object.setPrototypeOf ||
31158 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31159 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31160 return function (d, b) {
31161 extendStatics(d, b);
31162 function __() { this.constructor = d; }
31163 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31166 Object.defineProperty(exports, "__esModule", { value: true });
31167 var Error_1 = require("../../../Error");
31168 var GeometryTagError = /** @class */ (function (_super) {
31169 __extends(GeometryTagError, _super);
31170 function GeometryTagError(message) {
31171 var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
31172 _this.name = "GeometryTagError";
31175 return GeometryTagError;
31176 }(Error_1.MapillaryError));
31177 exports.GeometryTagError = GeometryTagError;
31178 exports.default = Error_1.MapillaryError;
31180 },{"../../../Error":283}],353:[function(require,module,exports){
31182 Object.defineProperty(exports, "__esModule", { value: true });
31183 var Subject_1 = require("rxjs/Subject");
31187 * @classdesc Represents a geometry.
31189 var Geometry = /** @class */ (function () {
31191 * Create a geometry.
31195 function Geometry() {
31196 this._notifyChanged$ = new Subject_1.Subject();
31198 Object.defineProperty(Geometry.prototype, "changed$", {
31200 * Get changed observable.
31202 * @description Emits the geometry itself every time the geometry
31205 * @returns {Observable<Geometry>} Observable emitting the geometry instance.
31209 return this._notifyChanged$;
31216 exports.Geometry = Geometry;
31217 exports.default = Geometry;
31219 },{"rxjs/Subject":34}],354:[function(require,module,exports){
31221 var __extends = (this && this.__extends) || (function () {
31222 var extendStatics = Object.setPrototypeOf ||
31223 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31224 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31225 return function (d, b) {
31226 extendStatics(d, b);
31227 function __() { this.constructor = d; }
31228 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31231 Object.defineProperty(exports, "__esModule", { value: true });
31232 var Component_1 = require("../../../Component");
31234 * @class PointGeometry
31236 * @classdesc Represents a point geometry in the 2D basic image coordinate system.
31240 * var basicPoint = [0.5, 0.7];
31241 * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
31244 var PointGeometry = /** @class */ (function (_super) {
31245 __extends(PointGeometry, _super);
31247 * Create a point geometry.
31250 * @param {Array<number>} point - An array representing the basic coordinates of
31253 * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
31255 function PointGeometry(point) {
31256 var _this = _super.call(this) || this;
31259 if (x < 0 || x > 1 || y < 0 || y > 1) {
31260 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
31262 _this._point = point.slice();
31265 Object.defineProperty(PointGeometry.prototype, "point", {
31267 * Get point property.
31268 * @returns {Array<number>} Array representing the basic coordinates of the point.
31271 return this._point;
31277 * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
31278 * basic coordinates of the point itself.
31280 * @returns {Array<number>} 2D basic coordinates representing the centroid.
31282 PointGeometry.prototype.getCentroid2d = function () {
31283 return this._point.slice();
31286 * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
31287 * world coordinates of the point itself.
31289 * @param {Transform} transform - The transform of the node related to the point.
31290 * @returns {Array<number>} 3D world coordinates representing the centroid.
31292 PointGeometry.prototype.getCentroid3d = function (transform) {
31293 return transform.unprojectBasic(this._point, 200);
31296 * Set the centroid of the point, i.e. the point coordinates.
31298 * @param {Array<number>} value - The new value of the centroid.
31299 * @param {Transform} transform - The transform of the node related to the point.
31301 PointGeometry.prototype.setCentroid2d = function (value, transform) {
31303 Math.max(0, Math.min(1, value[0])),
31304 Math.max(0, Math.min(1, value[1])),
31306 this._point[0] = changed[0];
31307 this._point[1] = changed[1];
31308 this._notifyChanged$.next(this);
31310 return PointGeometry;
31311 }(Component_1.Geometry));
31312 exports.PointGeometry = PointGeometry;
31314 },{"../../../Component":281}],355:[function(require,module,exports){
31316 var __extends = (this && this.__extends) || (function () {
31317 var extendStatics = Object.setPrototypeOf ||
31318 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31319 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31320 return function (d, b) {
31321 extendStatics(d, b);
31322 function __() { this.constructor = d; }
31323 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31326 Object.defineProperty(exports, "__esModule", { value: true });
31327 var Component_1 = require("../../../Component");
31329 * @class PolygonGeometry
31331 * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
31332 * All polygons and holes provided to the constructor needs to be closed.
31336 * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
31337 * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon);
31340 var PolygonGeometry = /** @class */ (function (_super) {
31341 __extends(PolygonGeometry, _super);
31343 * Create a polygon geometry.
31346 * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
31347 * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
31348 * Each array of holes vertices must be closed.
31350 * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
31352 function PolygonGeometry(polygon, holes) {
31353 var _this = _super.call(this) || this;
31354 var polygonLength = polygon.length;
31355 if (polygonLength < 3) {
31356 throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
31358 if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
31359 polygon[0][1] !== polygon[polygonLength - 1][1]) {
31360 throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
31362 _this._polygon = [];
31363 for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
31364 var vertex = polygon_1[_i];
31365 if (vertex[0] < 0 || vertex[0] > 1 ||
31366 vertex[1] < 0 || vertex[1] > 1) {
31367 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
31369 _this._polygon.push(vertex.slice());
31372 if (holes == null) {
31375 for (var i = 0; i < holes.length; i++) {
31376 var hole = holes[i];
31377 var holeLength = hole.length;
31378 if (holeLength < 3) {
31379 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
31381 if (hole[0][0] !== hole[holeLength - 1][0] ||
31382 hole[0][1] !== hole[holeLength - 1][1]) {
31383 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
31385 _this._holes.push([]);
31386 for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
31387 var vertex = hole_1[_a];
31388 if (vertex[0] < 0 || vertex[0] > 1 ||
31389 vertex[1] < 0 || vertex[1] > 1) {
31390 throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
31392 _this._holes[i].push(vertex.slice());
31397 Object.defineProperty(PolygonGeometry.prototype, "polygon", {
31399 * Get polygon property.
31400 * @returns {Array<Array<number>>} Closed 2d polygon.
31403 return this._polygon;
31408 Object.defineProperty(PolygonGeometry.prototype, "holes", {
31410 * Get holes property.
31411 * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
31414 return this._holes;
31420 * Add a vertex to the polygon by appending it after the last vertex.
31422 * @param {Array<number>} vertex - Vertex to add.
31424 PolygonGeometry.prototype.addVertex2d = function (vertex) {
31426 Math.max(0, Math.min(1, vertex[0])),
31427 Math.max(0, Math.min(1, vertex[1])),
31429 this._polygon.splice(this._polygon.length - 1, 0, clamped);
31430 this._notifyChanged$.next(this);
31433 * Get the coordinates of a vertex from the polygon representation of the geometry.
31435 * @description The first vertex represents the bottom-left corner with the rest of
31436 * the vertices following in clockwise order.
31438 * @param {number} index - Vertex index.
31439 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
31441 PolygonGeometry.prototype.getVertex2d = function (index) {
31442 return this._polygon[index].slice();
31445 * Remove a vertex from the polygon.
31447 * @param {number} index - The index of the vertex to remove.
31449 PolygonGeometry.prototype.removeVertex2d = function (index) {
31451 index >= this._polygon.length ||
31452 this._polygon.length < 4) {
31453 throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
31455 if (index > 0 && index < this._polygon.length - 1) {
31456 this._polygon.splice(index, 1);
31459 this._polygon.splice(0, 1);
31460 this._polygon.pop();
31461 var closing = this._polygon[0].slice();
31462 this._polygon.push(closing);
31464 this._notifyChanged$.next(this);
31467 PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
31469 Math.max(0, Math.min(1, value[0])),
31470 Math.max(0, Math.min(1, value[1])),
31472 if (index === 0 || index === this._polygon.length - 1) {
31473 this._polygon[0] = changed.slice();
31474 this._polygon[this._polygon.length - 1] = changed.slice();
31477 this._polygon[index] = changed.slice();
31479 this._notifyChanged$.next(this);
31482 PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
31483 var xs = this._polygon.map(function (point) { return point[0]; });
31484 var ys = this._polygon.map(function (point) { return point[1]; });
31485 var minX = Math.min.apply(Math, xs);
31486 var maxX = Math.max.apply(Math, xs);
31487 var minY = Math.min.apply(Math, ys);
31488 var maxY = Math.max.apply(Math, ys);
31489 var centroid = this.getCentroid2d();
31490 var minTranslationX = -minX;
31491 var maxTranslationX = 1 - maxX;
31492 var minTranslationY = -minY;
31493 var maxTranslationY = 1 - maxY;
31494 var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
31495 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
31496 for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
31497 var point = _a[_i];
31498 point[0] += translationX;
31499 point[1] += translationY;
31501 this._notifyChanged$.next(this);
31504 PolygonGeometry.prototype.getPoints3d = function (transform) {
31505 return this.getVertices3d(transform);
31508 PolygonGeometry.prototype.getVertex3d = function (index, transform) {
31509 return transform.unprojectBasic(this._polygon[index], 200);
31512 PolygonGeometry.prototype.getVertices2d = function () {
31513 return this._polygon.slice();
31516 PolygonGeometry.prototype.getVertices3d = function (transform) {
31517 return this._polygon
31518 .map(function (point) {
31519 return transform.unprojectBasic(point, 200);
31523 * Get a polygon representation of the 3D coordinates for the vertices of each hole
31526 * @param {Transform} transform - The transform of the node related to the geometry.
31527 * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
31528 * representing the vertices of each hole of the geometry.
31530 PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
31532 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
31535 .map(function (point) {
31536 return transform.unprojectBasic(point, 200);
31538 holes3d.push(hole3d);
31543 PolygonGeometry.prototype.getCentroid2d = function () {
31544 var polygon = this._polygon;
31548 for (var i = 0; i < polygon.length - 1; i++) {
31549 var xi = polygon[i][0];
31550 var yi = polygon[i][1];
31551 var xi1 = polygon[i + 1][0];
31552 var yi1 = polygon[i + 1][1];
31553 var a = xi * yi1 - xi1 * yi;
31555 centroidX += (xi + xi1) * a;
31556 centroidY += (yi + yi1) * a;
31559 centroidX /= 6 * area;
31560 centroidY /= 6 * area;
31561 return [centroidX, centroidY];
31564 PolygonGeometry.prototype.getCentroid3d = function (transform) {
31565 var centroid2d = this.getCentroid2d();
31566 return transform.unprojectBasic(centroid2d, 200);
31569 PolygonGeometry.prototype.getTriangles3d = function (transform) {
31570 return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
31573 PolygonGeometry.prototype.getPoleOfAccessibility2d = function () {
31574 return this._getPoleOfInaccessibility2d(this._polygon.slice());
31577 PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
31578 var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
31579 return transform.unprojectBasic(pole2d, 200);
31581 return PolygonGeometry;
31582 }(Component_1.VertexGeometry));
31583 exports.PolygonGeometry = PolygonGeometry;
31584 exports.default = PolygonGeometry;
31586 },{"../../../Component":281}],356:[function(require,module,exports){
31588 var __extends = (this && this.__extends) || (function () {
31589 var extendStatics = Object.setPrototypeOf ||
31590 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31591 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31592 return function (d, b) {
31593 extendStatics(d, b);
31594 function __() { this.constructor = d; }
31595 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31598 Object.defineProperty(exports, "__esModule", { value: true });
31599 var Component_1 = require("../../../Component");
31601 * @class RectGeometry
31603 * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
31607 * var basicRect = [0.5, 0.3, 0.7, 0.4];
31608 * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
31611 var RectGeometry = /** @class */ (function (_super) {
31612 __extends(RectGeometry, _super);
31614 * Create a rectangle geometry.
31617 * @param {Array<number>} rect - An array representing the top-left and bottom-right
31618 * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
31620 * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
31622 function RectGeometry(rect) {
31623 var _this = _super.call(this) || this;
31624 if (rect[1] > rect[3]) {
31625 throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
31627 for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
31628 var coord = rect_1[_i];
31629 if (coord < 0 || coord > 1) {
31630 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
31633 _this._anchorIndex = undefined;
31634 _this._rect = rect.slice(0, 4);
31635 _this._inverted = _this._rect[0] > _this._rect[2];
31638 Object.defineProperty(RectGeometry.prototype, "anchorIndex", {
31640 * Get anchor index property.
31642 * @returns {number} Index representing the current anchor property if
31643 * achoring indexing has been initialized. If anchor indexing has not been
31644 * initialized or has been terminated undefined will be returned.
31647 return this._anchorIndex;
31652 Object.defineProperty(RectGeometry.prototype, "inverted", {
31654 * Get inverted property.
31656 * @returns {boolean} Boolean determining whether the rect geometry is
31657 * inverted. For panoramas the rect geometrye may be inverted.
31660 return this._inverted;
31665 Object.defineProperty(RectGeometry.prototype, "rect", {
31667 * Get rect property.
31669 * @returns {Array<number>} Array representing the top-left and bottom-right
31670 * corners of the rectangle in basic coordinates.
31679 * Initialize anchor indexing to enable setting opposite vertex.
31681 * @param {number} [index] - The index of the vertex to use as anchor.
31683 * @throws {Error} If anchor indexing has already been initialized.
31684 * @throws {Error} If index is not valid (0 to 3).
31686 RectGeometry.prototype.initializeAnchorIndexing = function (index) {
31687 if (this._anchorIndex !== undefined) {
31688 throw new Error("Anchor indexing is already initialized.");
31690 if (index < 0 || index > 3) {
31691 throw new Error("Invalid anchor index: " + index + ".");
31693 this._anchorIndex = index === undefined ? 0 : index;
31696 * Terminate anchor indexing to disable setting pposite vertex.
31698 RectGeometry.prototype.terminateAnchorIndexing = function () {
31699 this._anchorIndex = undefined;
31702 * Set the value of the vertex opposite to the anchor in the polygon
31703 * representation of the rectangle.
31705 * @description Setting the opposite vertex may change the anchor index.
31707 * @param {Array<number>} opposite - The new value of the vertex opposite to the anchor.
31708 * @param {Transform} transform - The transform of the node related to the rectangle.
31710 * @throws {Error} When anchor indexing has not been initialized.
31712 RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) {
31713 if (this._anchorIndex === undefined) {
31714 throw new Error("Anchor indexing needs to be initialized.");
31717 Math.max(0, Math.min(1, opposite[0])),
31718 Math.max(0, Math.min(1, opposite[1])),
31720 var original = this._rect.slice();
31721 var anchor = this._anchorIndex === 0 ? [original[0], original[3]] :
31722 this._anchorIndex === 1 ? [original[0], original[1]] :
31723 this._anchorIndex === 2 ? [original[2], original[1]] :
31724 [original[2], original[3]];
31725 if (transform.fullPano) {
31726 var deltaX = this._anchorIndex < 2 ?
31727 changed[0] - original[2] :
31728 changed[0] - original[0];
31729 if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
31730 // right side passes boundary rightward
31731 this._inverted = true;
31732 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31734 else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
31735 // left side passes right side and boundary rightward
31736 this._inverted = true;
31737 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31739 else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) {
31740 this._inverted = false;
31741 if (anchor[0] > changed[0]) {
31742 // left side passes boundary rightward
31743 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31746 // left side passes right side and boundary rightward
31747 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31750 else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
31751 // left side passes boundary leftward
31752 this._inverted = true;
31753 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31755 else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
31756 // right side passes left side and boundary leftward
31757 this._inverted = true;
31758 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31760 else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) {
31761 this._inverted = false;
31762 if (anchor[0] > changed[0]) {
31763 // right side passes boundary leftward
31764 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31767 // right side passes left side and boundary leftward
31768 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31771 else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) {
31772 // inverted and right side passes left side completing a loop
31773 this._inverted = false;
31774 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31776 else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) {
31777 // inverted and left side passes right side completing a loop
31778 this._inverted = false;
31779 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31781 else if (this._inverted) {
31782 // if still inverted only top and bottom can switch
31783 if (this._anchorIndex < 2) {
31784 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31787 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31791 // if still not inverted treat as non full pano
31792 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
31793 this._anchorIndex = 0;
31795 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
31796 this._anchorIndex = 1;
31798 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
31799 this._anchorIndex = 2;
31802 this._anchorIndex = 3;
31806 if (this._anchorIndex === 0) {
31807 rect[0] = anchor[0];
31808 rect[1] = changed[1];
31809 rect[2] = changed[0];
31810 rect[3] = anchor[1];
31812 else if (this._anchorIndex === 1) {
31813 rect[0] = anchor[0];
31814 rect[1] = anchor[1];
31815 rect[2] = changed[0];
31816 rect[3] = changed[1];
31818 else if (this._anchorIndex === 2) {
31819 rect[0] = changed[0];
31820 rect[1] = anchor[1];
31821 rect[2] = anchor[0];
31822 rect[3] = changed[1];
31825 rect[0] = changed[0];
31826 rect[1] = changed[1];
31827 rect[2] = anchor[0];
31828 rect[3] = anchor[1];
31830 if (!this._inverted && rect[0] > rect[2] ||
31831 this._inverted && rect[0] < rect[2]) {
31832 rect[0] = original[0];
31833 rect[2] = original[2];
31835 if (rect[1] > rect[3]) {
31836 rect[1] = original[1];
31837 rect[3] = original[3];
31839 this._rect[0] = rect[0];
31840 this._rect[1] = rect[1];
31841 this._rect[2] = rect[2];
31842 this._rect[3] = rect[3];
31845 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
31846 this._anchorIndex = 0;
31848 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
31849 this._anchorIndex = 1;
31851 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
31852 this._anchorIndex = 2;
31855 this._anchorIndex = 3;
31858 if (this._anchorIndex === 0) {
31859 rect[0] = anchor[0];
31860 rect[1] = changed[1];
31861 rect[2] = changed[0];
31862 rect[3] = anchor[1];
31864 else if (this._anchorIndex === 1) {
31865 rect[0] = anchor[0];
31866 rect[1] = anchor[1];
31867 rect[2] = changed[0];
31868 rect[3] = changed[1];
31870 else if (this._anchorIndex === 2) {
31871 rect[0] = changed[0];
31872 rect[1] = anchor[1];
31873 rect[2] = anchor[0];
31874 rect[3] = changed[1];
31877 rect[0] = changed[0];
31878 rect[1] = changed[1];
31879 rect[2] = anchor[0];
31880 rect[3] = anchor[1];
31882 if (rect[0] > rect[2]) {
31883 rect[0] = original[0];
31884 rect[2] = original[2];
31886 if (rect[1] > rect[3]) {
31887 rect[1] = original[1];
31888 rect[3] = original[3];
31890 this._rect[0] = rect[0];
31891 this._rect[1] = rect[1];
31892 this._rect[2] = rect[2];
31893 this._rect[3] = rect[3];
31895 this._notifyChanged$.next(this);
31898 * Set the value of a vertex in the polygon representation of the rectangle.
31900 * @description The polygon is defined to have the first vertex at the
31901 * bottom-left corner with the rest of the vertices following in clockwise order.
31903 * @param {number} index - The index of the vertex to be set.
31904 * @param {Array<number>} value - The new value of the vertex.
31905 * @param {Transform} transform - The transform of the node related to the rectangle.
31907 RectGeometry.prototype.setVertex2d = function (index, value, transform) {
31908 var original = this._rect.slice();
31910 Math.max(0, Math.min(1, value[0])),
31911 Math.max(0, Math.min(1, value[1])),
31915 rect[0] = changed[0];
31916 rect[1] = original[1];
31917 rect[2] = original[2];
31918 rect[3] = changed[1];
31920 else if (index === 1) {
31921 rect[0] = changed[0];
31922 rect[1] = changed[1];
31923 rect[2] = original[2];
31924 rect[3] = original[3];
31926 else if (index === 2) {
31927 rect[0] = original[0];
31928 rect[1] = changed[1];
31929 rect[2] = changed[0];
31930 rect[3] = original[3];
31932 else if (index === 3) {
31933 rect[0] = original[0];
31934 rect[1] = original[1];
31935 rect[2] = changed[0];
31936 rect[3] = changed[1];
31938 if (transform.fullPano) {
31939 var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
31940 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
31941 var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
31942 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
31943 if (passingBoundaryLeftward || passingBoundaryRightward) {
31944 this._inverted = !this._inverted;
31947 if (rect[0] - original[0] < -0.25) {
31948 rect[0] = original[0];
31950 if (rect[2] - original[2] > 0.25) {
31951 rect[2] = original[2];
31954 if (!this._inverted && rect[0] > rect[2] ||
31955 this._inverted && rect[0] < rect[2]) {
31956 rect[0] = original[0];
31957 rect[2] = original[2];
31961 if (rect[0] > rect[2]) {
31962 rect[0] = original[0];
31963 rect[2] = original[2];
31966 if (rect[1] > rect[3]) {
31967 rect[1] = original[1];
31968 rect[3] = original[3];
31970 this._rect[0] = rect[0];
31971 this._rect[1] = rect[1];
31972 this._rect[2] = rect[2];
31973 this._rect[3] = rect[3];
31974 this._notifyChanged$.next(this);
31977 RectGeometry.prototype.setCentroid2d = function (value, transform) {
31978 var original = this._rect.slice();
31979 var x0 = original[0];
31980 var x1 = this._inverted ? original[2] + 1 : original[2];
31981 var y0 = original[1];
31982 var y1 = original[3];
31983 var centerX = x0 + (x1 - x0) / 2;
31984 var centerY = y0 + (y1 - y0) / 2;
31985 var translationX = 0;
31986 if (transform.gpano != null &&
31987 transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
31988 translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
31991 var minTranslationX = -x0;
31992 var maxTranslationX = 1 - x1;
31993 translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
31995 var minTranslationY = -y0;
31996 var maxTranslationY = 1 - y1;
31997 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
31998 this._rect[0] = original[0] + translationX;
31999 this._rect[1] = original[1] + translationY;
32000 this._rect[2] = original[2] + translationX;
32001 this._rect[3] = original[3] + translationY;
32002 if (this._rect[0] < 0) {
32003 this._rect[0] += 1;
32004 this._inverted = !this._inverted;
32006 else if (this._rect[0] > 1) {
32007 this._rect[0] -= 1;
32008 this._inverted = !this._inverted;
32010 if (this._rect[2] < 0) {
32011 this._rect[2] += 1;
32012 this._inverted = !this._inverted;
32014 else if (this._rect[2] > 1) {
32015 this._rect[2] -= 1;
32016 this._inverted = !this._inverted;
32018 this._notifyChanged$.next(this);
32021 * Get the 3D coordinates for the vertices of the rectangle with
32022 * interpolated points along the lines.
32024 * @param {Transform} transform - The transform of the node related to
32026 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
32027 * representing the rectangle.
32029 RectGeometry.prototype.getPoints3d = function (transform) {
32030 return this._getPoints2d(transform)
32031 .map(function (point) {
32032 return transform.unprojectBasic(point, 200);
32036 * Get the coordinates of a vertex from the polygon representation of the geometry.
32038 * @description The first vertex represents the bottom-left corner with the rest of
32039 * the vertices following in clockwise order. The method shifts the right side
32040 * coordinates of the rectangle by one unit to ensure that the vertices are ordered
32043 * @param {number} index - Vertex index.
32044 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
32046 RectGeometry.prototype.getVertex2d = function (index) {
32047 return this._rectToVertices2d(this._rect)[index];
32050 * Get the coordinates of a vertex from the polygon representation of the geometry.
32052 * @description The first vertex represents the bottom-left corner with the rest of
32053 * the vertices following in clockwise order. The coordinates will not be shifted
32054 * so they may not appear in clockwise order when layed out on the plane.
32056 * @param {number} index - Vertex index.
32057 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
32059 RectGeometry.prototype.getNonAdjustedVertex2d = function (index) {
32060 return this._rectToNonAdjustedVertices2d(this._rect)[index];
32063 * Get a vertex from the polygon representation of the 3D coordinates for the
32064 * vertices of the geometry.
32066 * @description The first vertex represents the bottom-left corner with the rest of
32067 * the vertices following in clockwise order.
32069 * @param {number} index - Vertex index.
32070 * @param {Transform} transform - The transform of the node related to the geometry.
32071 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
32072 * the vertices of the geometry.
32074 RectGeometry.prototype.getVertex3d = function (index, transform) {
32075 return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
32078 * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
32080 * @description The first vertex represents the bottom-left corner with the rest of
32081 * the vertices following in clockwise order.
32083 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
32084 * the rectangle vertices.
32086 RectGeometry.prototype.getVertices2d = function () {
32087 return this._rectToVertices2d(this._rect);
32090 * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
32092 * @description The first vertex represents the bottom-left corner with the rest of
32093 * the vertices following in clockwise order.
32095 * @param {Transform} transform - The transform of the node related to the rectangle.
32096 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
32097 * the rectangle vertices.
32099 RectGeometry.prototype.getVertices3d = function (transform) {
32100 return this._rectToVertices2d(this._rect)
32101 .map(function (vertex) {
32102 return transform.unprojectBasic(vertex, 200);
32106 RectGeometry.prototype.getCentroid2d = function () {
32107 var rect = this._rect;
32109 var x1 = this._inverted ? rect[2] + 1 : rect[2];
32112 var centroidX = x0 + (x1 - x0) / 2;
32113 var centroidY = y0 + (y1 - y0) / 2;
32114 return [centroidX, centroidY];
32117 RectGeometry.prototype.getCentroid3d = function (transform) {
32118 var centroid2d = this.getCentroid2d();
32119 return transform.unprojectBasic(centroid2d, 200);
32122 RectGeometry.prototype.getPoleOfAccessibility2d = function () {
32123 return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
32126 RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
32127 var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
32128 return transform.unprojectBasic(pole2d, 200);
32131 RectGeometry.prototype.getTriangles3d = function (transform) {
32132 return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
32135 * Check if a particular bottom-right value is valid according to the current
32136 * rectangle coordinates.
32138 * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
32139 * @returns {boolean} Value indicating whether the provided bottom-right coordinates
32142 RectGeometry.prototype.validate = function (bottomRight) {
32143 var rect = this._rect;
32144 if (!this._inverted && bottomRight[0] < rect[0] ||
32145 bottomRight[0] - rect[2] > 0.25 ||
32146 bottomRight[1] < rect[1]) {
32152 * Get the 2D coordinates for the vertices of the rectangle with
32153 * interpolated points along the lines.
32155 * @param {Transform} transform - The transform of the node related to
32157 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
32158 * representing the rectangle.
32160 RectGeometry.prototype._getPoints2d = function (transform) {
32161 var vertices2d = this._rectToVertices2d(this._rect);
32162 var sides = vertices2d.length - 1;
32165 for (var i = 0; i < sides; ++i) {
32166 var startX = vertices2d[i][0];
32167 var startY = vertices2d[i][1];
32168 var endX = vertices2d[i + 1][0];
32169 var endY = vertices2d[i + 1][1];
32170 var intervalX = (endX - startX) / (sections - 1);
32171 var intervalY = (endY - startY) / (sections - 1);
32172 for (var j = 0; j < sections; ++j) {
32174 startX + j * intervalX,
32175 startY + j * intervalY,
32177 points2d.push(point);
32183 * Convert the top-left, bottom-right representation of a rectangle to a polygon
32184 * representation of the vertices starting at the bottom-left corner going
32187 * @description The method shifts the right side coordinates of the rectangle
32188 * by one unit to ensure that the vertices are ordered clockwise.
32190 * @param {Array<number>} rect - Top-left, bottom-right representation of a
32192 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
32195 RectGeometry.prototype._rectToVertices2d = function (rect) {
32197 [rect[0], rect[3]],
32198 [rect[0], rect[1]],
32199 [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
32200 [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
32201 [rect[0], rect[3]],
32205 * Convert the top-left, bottom-right representation of a rectangle to a polygon
32206 * representation of the vertices starting at the bottom-left corner going
32209 * @description The first vertex represents the bottom-left corner with the rest of
32210 * the vertices following in clockwise order. The coordinates will not be shifted
32211 * to ensure that the vertices are ordered clockwise when layed out on the plane.
32213 * @param {Array<number>} rect - Top-left, bottom-right representation of a
32215 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
32218 RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) {
32220 [rect[0], rect[3]],
32221 [rect[0], rect[1]],
32222 [rect[2], rect[1]],
32223 [rect[2], rect[3]],
32224 [rect[0], rect[3]],
32227 return RectGeometry;
32228 }(Component_1.VertexGeometry));
32229 exports.RectGeometry = RectGeometry;
32230 exports.default = RectGeometry;
32232 },{"../../../Component":281}],357:[function(require,module,exports){
32234 /// <reference path="../../../../typings/index.d.ts" />
32235 var __extends = (this && this.__extends) || (function () {
32236 var extendStatics = Object.setPrototypeOf ||
32237 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32238 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32239 return function (d, b) {
32240 extendStatics(d, b);
32241 function __() { this.constructor = d; }
32242 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32245 Object.defineProperty(exports, "__esModule", { value: true });
32246 var earcut = require("earcut");
32247 var polylabel = require("@mapbox/polylabel");
32248 var Component_1 = require("../../../Component");
32250 * @class VertexGeometry
32252 * @classdesc Represents a vertex geometry.
32254 var VertexGeometry = /** @class */ (function (_super) {
32255 __extends(VertexGeometry, _super);
32257 * Create a vertex geometry.
32261 function VertexGeometry() {
32262 return _super.call(this) || this;
32265 * Finds the polygon pole of inaccessibility, the most distant internal
32266 * point from the polygon outline.
32268 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
32269 * @returns {Array<number>} Point of inaccessibility.
32272 VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
32273 var pole2d = polylabel([points2d], 3e-2);
32277 * Triangulates a 2d polygon and returns the triangle
32278 * representation as a flattened array of 3d points.
32280 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
32281 * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
32282 * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
32283 * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
32284 * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
32287 VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
32288 var data = [points2d.slice(0, -1)];
32289 for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
32290 var hole2d = _a[_i];
32291 data.push(hole2d.slice(0, -1));
32293 var points = points3d.slice(0, -1);
32294 for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
32295 var hole3d = _c[_b];
32296 points = points.concat(hole3d.slice(0, -1));
32298 var flattened = earcut.flatten(data);
32299 var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
32300 var triangles = [];
32301 for (var i = 0; i < indices.length; ++i) {
32302 var point = points[indices[i]];
32303 triangles.push(point[0]);
32304 triangles.push(point[1]);
32305 triangles.push(point[2]);
32309 return VertexGeometry;
32310 }(Component_1.Geometry));
32311 exports.VertexGeometry = VertexGeometry;
32312 exports.default = VertexGeometry;
32314 },{"../../../Component":281,"@mapbox/polylabel":1,"earcut":8}],358:[function(require,module,exports){
32316 /// <reference path="../../../../typings/index.d.ts" />
32317 var __extends = (this && this.__extends) || (function () {
32318 var extendStatics = Object.setPrototypeOf ||
32319 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32320 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32321 return function (d, b) {
32322 extendStatics(d, b);
32323 function __() { this.constructor = d; }
32324 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32327 Object.defineProperty(exports, "__esModule", { value: true });
32328 var Subject_1 = require("rxjs/Subject");
32329 var Component_1 = require("../../../Component");
32330 var CreateHandlerBase = /** @class */ (function (_super) {
32331 __extends(CreateHandlerBase, _super);
32332 function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) {
32333 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
32334 _this._tagCreator = tagCreator;
32335 _this._geometryCreated$ = new Subject_1.Subject();
32338 Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", {
32340 return this._geometryCreated$;
32345 CreateHandlerBase.prototype._enable = function () {
32346 this._enableCreate();
32347 this._container.element.classList.add("component-tag-create");
32349 CreateHandlerBase.prototype._disable = function () {
32350 this._container.element.classList.remove("component-tag-create");
32351 this._disableCreate();
32353 CreateHandlerBase.prototype._validateBasic = function (basic) {
32356 return 0 <= x && x <= 1 && 0 <= y && y <= 1;
32358 CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) {
32361 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
32362 .map(function (_a) {
32363 var event = _a[0], camera = _a[1], transform = _a[2];
32364 return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
32367 return CreateHandlerBase;
32368 }(Component_1.TagHandlerBase));
32369 exports.CreateHandlerBase = CreateHandlerBase;
32370 exports.default = CreateHandlerBase;
32372 },{"../../../Component":281,"rxjs/Subject":34}],359:[function(require,module,exports){
32374 var __extends = (this && this.__extends) || (function () {
32375 var extendStatics = Object.setPrototypeOf ||
32376 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32377 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32378 return function (d, b) {
32379 extendStatics(d, b);
32380 function __() { this.constructor = d; }
32381 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32384 Object.defineProperty(exports, "__esModule", { value: true });
32385 var Component_1 = require("../../../Component");
32386 var CreatePointHandler = /** @class */ (function (_super) {
32387 __extends(CreatePointHandler, _super);
32388 function CreatePointHandler() {
32389 return _super !== null && _super.apply(this, arguments) || this;
32391 CreatePointHandler.prototype._enableCreate = function () {
32392 this._container.mouseService.deferPixels(this._name, 4);
32393 this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$)
32394 .filter(this._validateBasic)
32395 .map(function (basic) {
32396 return new Component_1.PointGeometry(basic);
32398 .subscribe(this._geometryCreated$);
32400 CreatePointHandler.prototype._disableCreate = function () {
32401 this._container.mouseService.undeferPixels(this._name);
32402 this._geometryCreatedSubscription.unsubscribe();
32404 CreatePointHandler.prototype._getNameExtension = function () {
32405 return "create-point";
32407 return CreatePointHandler;
32408 }(Component_1.CreateHandlerBase));
32409 exports.CreatePointHandler = CreatePointHandler;
32410 exports.default = CreatePointHandler;
32412 },{"../../../Component":281}],360:[function(require,module,exports){
32414 var __extends = (this && this.__extends) || (function () {
32415 var extendStatics = Object.setPrototypeOf ||
32416 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32417 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32418 return function (d, b) {
32419 extendStatics(d, b);
32420 function __() { this.constructor = d; }
32421 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32424 Object.defineProperty(exports, "__esModule", { value: true });
32425 var Component_1 = require("../../../Component");
32426 var CreatePolygonHandler = /** @class */ (function (_super) {
32427 __extends(CreatePolygonHandler, _super);
32428 function CreatePolygonHandler() {
32429 return _super !== null && _super.apply(this, arguments) || this;
32431 CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) {
32432 tag.addPoint(basicPoint);
32434 Object.defineProperty(CreatePolygonHandler.prototype, "_create$", {
32436 return this._tagCreator.createPolygon$;
32441 CreatePolygonHandler.prototype._getNameExtension = function () {
32442 return "create-polygon";
32444 CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
32445 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform);
32447 return CreatePolygonHandler;
32448 }(Component_1.CreateVertexHandler));
32449 exports.CreatePolygonHandler = CreatePolygonHandler;
32450 exports.default = CreatePolygonHandler;
32452 },{"../../../Component":281}],361:[function(require,module,exports){
32454 var __extends = (this && this.__extends) || (function () {
32455 var extendStatics = Object.setPrototypeOf ||
32456 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32457 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32458 return function (d, b) {
32459 extendStatics(d, b);
32460 function __() { this.constructor = d; }
32461 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32464 Object.defineProperty(exports, "__esModule", { value: true });
32465 var Observable_1 = require("rxjs/Observable");
32466 var Component_1 = require("../../../Component");
32467 var CreateRectDragHandler = /** @class */ (function (_super) {
32468 __extends(CreateRectDragHandler, _super);
32469 function CreateRectDragHandler() {
32470 return _super !== null && _super.apply(this, arguments) || this;
32472 CreateRectDragHandler.prototype._enableCreate = function () {
32474 this._container.mouseService.claimMouse(this._name, 2);
32475 this._deleteSubscription = this._navigator.stateService.currentTransform$
32476 .map(function (transform) { return null; })
32478 .subscribe(this._tagCreator.delete$);
32479 this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$))
32480 .filter(this._validateBasic)
32481 .subscribe(this._tagCreator.createRect$);
32482 this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
32483 .filter(function (tag) {
32486 .subscribe(function (tag) {
32487 tag.geometry.initializeAnchorIndexing();
32489 var basicMouse$ = Observable_1.Observable
32490 .merge(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseMove$), this._container.mouseService.filtered$(this._name, this._container.mouseService.domMouseMove$))
32491 .combineLatest(this._container.renderService.renderCamera$)
32492 .withLatestFrom(this._navigator.stateService.currentTransform$)
32493 .map(function (_a) {
32494 var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1];
32495 return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
32497 this._setVertexSubscription = this._tagCreator.tag$
32498 .switchMap(function (tag) {
32500 Observable_1.Observable
32501 .combineLatest(Observable_1.Observable.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) :
32502 Observable_1.Observable.empty();
32504 .subscribe(function (_a) {
32505 var tag = _a[0], basicPoint = _a[1], transform = _a[2];
32506 tag.geometry.setOppositeVertex2d(basicPoint, transform);
32508 var basicMouseDragEnd$ = this._container.mouseService.mouseDragEnd$
32509 .withLatestFrom(this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDrag$))
32510 .filter(this._validateBasic), function (event, basicPoint) {
32514 this._addPointSubscription = this._tagCreator.tag$
32515 .switchMap(function (tag) {
32517 Observable_1.Observable
32518 .combineLatest(Observable_1.Observable.of(tag), basicMouseDragEnd$) :
32519 Observable_1.Observable.empty();
32521 .subscribe(function (_a) {
32522 var tag = _a[0], basicPoint = _a[1];
32523 var rectGeometry = tag.geometry;
32524 if (!rectGeometry.validate(basicPoint)) {
32525 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
32527 tag.addPoint(basicPoint);
32529 this._geometryCreatedSubscription = this._tagCreator.tag$
32530 .switchMap(function (tag) {
32533 .map(function (t) {
32536 Observable_1.Observable.empty();
32538 .subscribe(this._geometryCreated$);
32540 CreateRectDragHandler.prototype._disableCreate = function () {
32541 this._container.mouseService.unclaimMouse(this._name);
32542 this._tagCreator.delete$.next(null);
32543 this._addPointSubscription.unsubscribe();
32544 this._createSubscription.unsubscribe();
32545 this._deleteSubscription.unsubscribe();
32546 this._geometryCreatedSubscription.unsubscribe();
32547 this._initializeAnchorIndexingSubscription.unsubscribe();
32548 this._setVertexSubscription.unsubscribe();
32550 CreateRectDragHandler.prototype._getNameExtension = function () {
32551 return "create-rect-drag";
32553 return CreateRectDragHandler;
32554 }(Component_1.CreateHandlerBase));
32555 exports.CreateRectDragHandler = CreateRectDragHandler;
32556 exports.default = CreateRectDragHandler;
32558 },{"../../../Component":281,"rxjs/Observable":29}],362:[function(require,module,exports){
32560 var __extends = (this && this.__extends) || (function () {
32561 var extendStatics = Object.setPrototypeOf ||
32562 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32563 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32564 return function (d, b) {
32565 extendStatics(d, b);
32566 function __() { this.constructor = d; }
32567 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32570 Object.defineProperty(exports, "__esModule", { value: true });
32571 var Component_1 = require("../../../Component");
32572 var CreateRectHandler = /** @class */ (function (_super) {
32573 __extends(CreateRectHandler, _super);
32574 function CreateRectHandler() {
32575 return _super !== null && _super.apply(this, arguments) || this;
32577 Object.defineProperty(CreateRectHandler.prototype, "_create$", {
32579 return this._tagCreator.createRect$;
32584 CreateRectHandler.prototype._addPoint = function (tag, basicPoint) {
32585 var rectGeometry = tag.geometry;
32586 if (!rectGeometry.validate(basicPoint)) {
32587 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
32589 tag.addPoint(basicPoint);
32591 CreateRectHandler.prototype._enable = function () {
32592 _super.prototype._enable.call(this);
32593 this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
32594 .filter(function (tag) {
32597 .subscribe(function (tag) {
32598 tag.geometry.initializeAnchorIndexing();
32601 CreateRectHandler.prototype._disable = function () {
32602 _super.prototype._disable.call(this);
32603 this._initializeAnchorIndexingSubscription.unsubscribe();
32605 CreateRectHandler.prototype._getNameExtension = function () {
32606 return "create-rect";
32608 CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
32609 tag.geometry.setOppositeVertex2d(basicPoint, transform);
32611 return CreateRectHandler;
32612 }(Component_1.CreateVertexHandler));
32613 exports.CreateRectHandler = CreateRectHandler;
32614 exports.default = CreateRectHandler;
32616 },{"../../../Component":281}],363:[function(require,module,exports){
32618 var __extends = (this && this.__extends) || (function () {
32619 var extendStatics = Object.setPrototypeOf ||
32620 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32621 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32622 return function (d, b) {
32623 extendStatics(d, b);
32624 function __() { this.constructor = d; }
32625 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32628 Object.defineProperty(exports, "__esModule", { value: true });
32629 var Observable_1 = require("rxjs/Observable");
32630 var Component_1 = require("../../../Component");
32631 var CreateVertexHandler = /** @class */ (function (_super) {
32632 __extends(CreateVertexHandler, _super);
32633 function CreateVertexHandler() {
32634 return _super !== null && _super.apply(this, arguments) || this;
32636 CreateVertexHandler.prototype._enableCreate = function () {
32638 this._container.mouseService.deferPixels(this._name, 4);
32639 var transformChanged$ = this._navigator.stateService.currentTransform$
32640 .map(function (transform) { })
32643 this._deleteSubscription = transformChanged$
32645 .subscribe(this._tagCreator.delete$);
32646 var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).share();
32647 this._createSubscription = transformChanged$
32648 .switchMap(function () {
32650 .filter(_this._validateBasic)
32653 .subscribe(this._create$);
32654 this._setVertexSubscription = this._tagCreator.tag$
32655 .switchMap(function (tag) {
32657 Observable_1.Observable
32658 .combineLatest(Observable_1.Observable.of(tag), Observable_1.Observable
32659 .merge(_this._container.mouseService.mouseMove$, _this._container.mouseService.domMouseMove$), _this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$) :
32660 Observable_1.Observable.empty();
32662 .subscribe(function (_a) {
32663 var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3];
32664 var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
32665 _this._setVertex2d(tag, basicPoint, transform);
32667 this._addPointSubscription = this._tagCreator.tag$
32668 .switchMap(function (tag) {
32670 Observable_1.Observable
32671 .combineLatest(Observable_1.Observable.of(tag), basicClick$) :
32672 Observable_1.Observable.empty();
32674 .subscribe(function (_a) {
32675 var tag = _a[0], basicPoint = _a[1];
32676 _this._addPoint(tag, basicPoint);
32678 this._geometryCreateSubscription = this._tagCreator.tag$
32679 .switchMap(function (tag) {
32682 .map(function (t) {
32685 Observable_1.Observable.empty();
32687 .subscribe(this._geometryCreated$);
32689 CreateVertexHandler.prototype._disableCreate = function () {
32690 this._container.mouseService.undeferPixels(this._name);
32691 this._tagCreator.delete$.next(null);
32692 this._addPointSubscription.unsubscribe();
32693 this._createSubscription.unsubscribe();
32694 this._deleteSubscription.unsubscribe();
32695 this._geometryCreateSubscription.unsubscribe();
32696 this._setVertexSubscription.unsubscribe();
32698 return CreateVertexHandler;
32699 }(Component_1.CreateHandlerBase));
32700 exports.CreateVertexHandler = CreateVertexHandler;
32701 exports.default = CreateVertexHandler;
32703 },{"../../../Component":281,"rxjs/Observable":29}],364:[function(require,module,exports){
32705 var __extends = (this && this.__extends) || (function () {
32706 var extendStatics = Object.setPrototypeOf ||
32707 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32708 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32709 return function (d, b) {
32710 extendStatics(d, b);
32711 function __() { this.constructor = d; }
32712 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32715 Object.defineProperty(exports, "__esModule", { value: true });
32716 var Observable_1 = require("rxjs/Observable");
32717 var Component_1 = require("../../../Component");
32718 var EditVertexHandler = /** @class */ (function (_super) {
32719 __extends(EditVertexHandler, _super);
32720 function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) {
32721 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
32722 _this._tagSet = tagSet;
32725 EditVertexHandler.prototype._enable = function () {
32727 var interaction$ = this._tagSet.changed$
32728 .map(function (tagSet) {
32729 return tagSet.getAll();
32731 .switchMap(function (tags) {
32732 return Observable_1.Observable
32734 .mergeMap(function (tag) {
32735 return tag.interact$;
32738 .switchMap(function (interaction) {
32739 return Observable_1.Observable
32741 .concat(_this._container.mouseService.documentMouseUp$
32743 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
32748 var mouseMove$ = Observable_1.Observable
32749 .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$)
32751 this._claimMouseSubscription = interaction$
32752 .switchMap(function (interaction) {
32753 return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : Observable_1.Observable.empty();
32755 .subscribe(function () {
32756 _this._container.mouseService.claimMouse(_this._name, 3);
32758 this._cursorSubscription = interaction$
32759 .map(function (interaction) {
32760 return interaction.cursor;
32762 .distinctUntilChanged()
32763 .subscribe(function (cursor) {
32764 var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"];
32765 for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) {
32766 var interactionCursor = interactionCursors_1[_i];
32767 _this._container.element.classList.remove("component-tag-edit-" + interactionCursor);
32770 _this._container.element.classList.add("component-tag-edit-" + cursor);
32773 this._unclaimMouseSubscription = this._container.mouseService
32774 .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
32775 .subscribe(function (e) {
32776 _this._container.mouseService.unclaimMouse(_this._name);
32778 this._preventDefaultSubscription = interaction$
32779 .switchMap(function (interaction) {
32780 return !!interaction.tag ?
32781 _this._container.mouseService.documentMouseMove$ :
32782 Observable_1.Observable.empty();
32784 .subscribe(function (event) {
32785 event.preventDefault(); // prevent selection of content outside the viewer
32787 this._updateGeometrySubscription = interaction$
32788 .withLatestFrom(mouseMove$)
32789 .switchMap(function (_a) {
32790 var interaction = _a[0], mouseMove = _a[1];
32791 if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) {
32792 return Observable_1.Observable.empty();
32794 var mouseDrag$ = Observable_1.Observable
32796 .concat(_this._container.mouseService
32797 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$)
32798 .filter(function (event) {
32799 return _this._viewportCoords.insideElement(event, _this._container.element);
32801 return Observable_1.Observable
32802 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
32803 .withLatestFrom(Observable_1.Observable.of(interaction), _this._navigator.stateService.currentTransform$, function (_a, i, transform) {
32804 var event = _a[0], render = _a[1];
32805 return [event, render, i, transform];
32808 .subscribe(function (_a) {
32809 var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3];
32810 var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY);
32811 var geometry = interaction.tag.geometry;
32812 if (interaction.operation === Component_1.TagOperation.Centroid) {
32813 geometry.setCentroid2d(basic, transform);
32815 else if (interaction.operation === Component_1.TagOperation.Vertex) {
32816 geometry.setVertex2d(interaction.vertexIndex, basic, transform);
32820 EditVertexHandler.prototype._disable = function () {
32821 this._claimMouseSubscription.unsubscribe();
32822 this._cursorSubscription.unsubscribe();
32823 this._preventDefaultSubscription.unsubscribe();
32824 this._unclaimMouseSubscription.unsubscribe();
32825 this._updateGeometrySubscription.unsubscribe();
32827 EditVertexHandler.prototype._getNameExtension = function () {
32828 return "edit-vertex";
32830 return EditVertexHandler;
32831 }(Component_1.TagHandlerBase));
32832 exports.EditVertexHandler = EditVertexHandler;
32833 exports.default = EditVertexHandler;
32835 },{"../../../Component":281,"rxjs/Observable":29}],365:[function(require,module,exports){
32837 /// <reference path="../../../../typings/index.d.ts" />
32838 var __extends = (this && this.__extends) || (function () {
32839 var extendStatics = Object.setPrototypeOf ||
32840 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32841 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32842 return function (d, b) {
32843 extendStatics(d, b);
32844 function __() { this.constructor = d; }
32845 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32848 Object.defineProperty(exports, "__esModule", { value: true });
32849 var Component_1 = require("../../../Component");
32850 var TagHandlerBase = /** @class */ (function (_super) {
32851 __extends(TagHandlerBase, _super);
32852 function TagHandlerBase(component, container, navigator, viewportCoords) {
32853 var _this = _super.call(this, component, container, navigator) || this;
32854 _this._name = _this._component.name + "-" + _this._getNameExtension();
32855 _this._viewportCoords = viewportCoords;
32858 TagHandlerBase.prototype._getConfiguration = function (enable) {
32861 TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
32862 offsetX = offsetX != null ? offsetX : 0;
32863 offsetY = offsetY != null ? offsetY : 0;
32864 var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
32865 var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
32868 return TagHandlerBase;
32869 }(Component_1.HandlerBase));
32870 exports.TagHandlerBase = TagHandlerBase;
32871 exports.default = TagHandlerBase;
32873 },{"../../../Component":281}],366:[function(require,module,exports){
32875 /// <reference path="../../../../typings/index.d.ts" />
32876 Object.defineProperty(exports, "__esModule", { value: true });
32877 var THREE = require("three");
32878 var vd = require("virtual-dom");
32879 var Subject_1 = require("rxjs/Subject");
32880 var Component_1 = require("../../../Component");
32881 var Geo_1 = require("../../../Geo");
32882 var OutlineCreateTag = /** @class */ (function () {
32883 function OutlineCreateTag(geometry, options, transform, viewportCoords) {
32885 this._geometry = geometry;
32886 this._options = { color: options.color == null ? 0xFFFFFF : options.color };
32887 this._transform = transform;
32888 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
32889 this._outline = this._createOutine();
32890 this._glObjects = [this._outline];
32891 this._aborted$ = new Subject_1.Subject();
32892 this._created$ = new Subject_1.Subject();
32893 this._glObjectsChanged$ = new Subject_1.Subject();
32894 this._geometryChangedSubscription = this._geometry.changed$
32895 .subscribe(function (vertexGeometry) {
32896 _this._disposeOutline();
32897 _this._outline = _this._createOutine();
32898 _this._glObjects = [_this._outline];
32899 _this._glObjectsChanged$.next(_this);
32902 Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
32904 return this._geometry;
32909 Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
32911 return this._glObjects;
32916 Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
32918 return this._aborted$;
32923 Object.defineProperty(OutlineCreateTag.prototype, "created$", {
32925 return this._created$;
32930 Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
32932 return this._glObjectsChanged$;
32937 Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
32940 return this._geometry.changed$
32941 .map(function (geometry) {
32948 OutlineCreateTag.prototype.dispose = function () {
32949 this._disposeOutline();
32950 this._geometryChangedSubscription.unsubscribe();
32952 OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
32956 offsetHeight: size.height, offsetWidth: size.width,
32958 var abort = function (e) {
32959 e.stopPropagation();
32960 _this._aborted$.next(_this);
32962 if (this._geometry instanceof Component_1.RectGeometry) {
32963 var anchorIndex = this._geometry.anchorIndex;
32964 var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex;
32965 var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1];
32966 var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
32967 if (canvasPoint != null) {
32968 var background = this._colorToBackground(this._options.color);
32969 var transform = this._canvasToTransform(canvasPoint);
32970 var pointProperties = {
32971 style: { background: background, transform: transform },
32973 var completerProperties = {
32975 style: { transform: transform },
32977 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
32978 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
32981 else if (this._geometry instanceof Component_1.PolygonGeometry) {
32982 var polygonGeometry_1 = this._geometry;
32983 var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
32984 var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
32985 if (firstVertexCanvas != null) {
32986 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
32988 e.stopPropagation();
32989 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
32990 _this._created$.next(_this);
32993 var transform = this._canvasToTransform(firstVertexCanvas);
32994 var completerProperties = {
32995 onclick: firstOnclick,
32996 style: { transform: transform },
32998 var firstClass = polygonGeometry_1.polygon.length > 4 ?
33001 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
33003 if (polygonGeometry_1.polygon.length > 3) {
33004 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
33005 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
33006 if (lastVertexCanvas != null) {
33007 var remove = function (e) {
33008 e.stopPropagation();
33009 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
33011 var transform = this._canvasToTransform(lastVertexCanvas);
33012 var completerProperties = {
33014 style: { transform: transform },
33016 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
33019 var verticesBasic = polygonGeometry_1.polygon.slice();
33020 verticesBasic.splice(-2, 2);
33021 for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
33022 var vertexBasic = verticesBasic_1[_i];
33023 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
33024 if (vertexCanvas != null) {
33025 var background = this._colorToBackground(this._options.color);
33026 var transform = this._canvasToTransform(vertexCanvas);
33027 var pointProperties = {
33029 background: background,
33030 transform: transform,
33033 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
33039 OutlineCreateTag.prototype.addPoint = function (point) {
33040 if (this._geometry instanceof Component_1.RectGeometry) {
33041 var rectGeometry = this._geometry;
33042 if (!rectGeometry.validate(point)) {
33045 this._created$.next(this);
33047 else if (this._geometry instanceof Component_1.PolygonGeometry) {
33048 var polygonGeometry = this._geometry;
33049 polygonGeometry.addVertex2d(point);
33052 OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
33053 var canvasX = Math.round(canvas[0]);
33054 var canvasY = Math.round(canvas[1]);
33055 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
33058 OutlineCreateTag.prototype._colorToBackground = function (color) {
33059 return "#" + ("000000" + color.toString(16)).substr(-6);
33061 OutlineCreateTag.prototype._createOutine = function () {
33062 var polygon3d = this._geometry.getPoints3d(this._transform);
33063 var positions = this._getLinePositions(polygon3d);
33064 var geometry = new THREE.BufferGeometry();
33065 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33066 var material = new THREE.LineBasicMaterial({
33067 color: this._options.color,
33070 return new THREE.Line(geometry, material);
33072 OutlineCreateTag.prototype._disposeOutline = function () {
33073 if (this._outline == null) {
33076 var line = this._outline;
33077 line.geometry.dispose();
33078 line.material.dispose();
33079 this._outline = null;
33080 this._glObjects = [];
33082 OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
33083 var length = polygon3d.length;
33084 var positions = new Float32Array(length * 3);
33085 for (var i = 0; i < length; ++i) {
33087 var position = polygon3d[i];
33088 positions[index] = position[0];
33089 positions[index + 1] = position[1];
33090 positions[index + 2] = position[2];
33094 return OutlineCreateTag;
33096 exports.OutlineCreateTag = OutlineCreateTag;
33097 exports.default = OutlineCreateTag;
33099 },{"../../../Component":281,"../../../Geo":284,"rxjs/Subject":34,"three":231,"virtual-dom":237}],367:[function(require,module,exports){
33101 /// <reference path="../../../../typings/index.d.ts" />
33102 var __extends = (this && this.__extends) || (function () {
33103 var extendStatics = Object.setPrototypeOf ||
33104 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33105 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33106 return function (d, b) {
33107 extendStatics(d, b);
33108 function __() { this.constructor = d; }
33109 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33112 Object.defineProperty(exports, "__esModule", { value: true });
33113 var THREE = require("three");
33114 var vd = require("virtual-dom");
33115 var Component_1 = require("../../../Component");
33117 * @class OutlineRenderTag
33118 * @classdesc Tag visualizing the properties of an OutlineTag.
33120 var OutlineRenderTag = /** @class */ (function (_super) {
33121 __extends(OutlineRenderTag, _super);
33122 function OutlineRenderTag(tag, transform) {
33123 var _this = _super.call(this, tag, transform) || this;
33124 _this._fill = !transform.gpano ?
33125 _this._createFill() :
33127 _this._holes = _this._tag.lineWidth >= 1 ?
33128 _this._createHoles() :
33130 _this._outline = _this._tag.lineWidth >= 1 ?
33131 _this._createOutline() :
33133 _this._geometryChangedSubscription = _this._tag.geometry.changed$
33134 .subscribe(function (geometry) {
33135 if (_this._fill != null) {
33136 _this._updateFillGeometry();
33138 if (_this._holes.length > 0) {
33139 _this._updateHoleGeometries();
33141 if (_this._outline != null) {
33142 _this._updateOulineGeometry();
33145 _this._changedSubscription = _this._tag.changed$
33146 .subscribe(function (changedTag) {
33147 var glObjectsChanged = false;
33148 if (_this._fill != null) {
33149 _this._updateFillMaterial(_this._fill.material);
33151 if (_this._outline == null) {
33152 if (_this._tag.lineWidth >= 1) {
33153 _this._holes = _this._createHoles();
33154 _this._outline = _this._createOutline();
33155 glObjectsChanged = true;
33159 _this._updateHoleMaterials();
33160 _this._updateOutlineMaterial();
33162 if (glObjectsChanged) {
33163 _this._glObjectsChanged$.next(_this);
33168 OutlineRenderTag.prototype.dispose = function () {
33169 this._disposeFill();
33170 this._disposeHoles();
33171 this._disposeOutline();
33172 this._changedSubscription.unsubscribe();
33173 this._geometryChangedSubscription.unsubscribe();
33175 OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
33178 var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
33179 var isPerspective = !this._transform.gpano;
33181 offsetHeight: size.height, offsetWidth: size.width,
33183 if (this._tag.icon != null && (isRect || isPerspective)) {
33184 var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
33185 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
33186 this._tag.geometry.getPoleOfAccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
33187 var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
33188 if (iconCanvas != null) {
33189 var interact = function (e) {
33190 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
33192 if (atlas.loaded) {
33193 var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
33194 var iconCanvasX = Math.round(iconCanvas[0]);
33195 var iconCanvasY = Math.round(iconCanvas[1]);
33196 var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
33197 var click = function (e) {
33198 e.stopPropagation();
33199 _this._tag.click$.next(_this._tag);
33203 onmousedown: interact,
33204 style: { transform: transform },
33206 vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
33210 else if (this._tag.text != null && (isRect || isPerspective)) {
33211 var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
33212 this._tag.geometry.getVertex2d(3) :
33213 this._tag.geometry.getPoleOfAccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
33214 var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
33215 if (textCanvas != null) {
33216 var textCanvasX = Math.round(textCanvas[0]);
33217 var textCanvasY = Math.round(textCanvas[1]);
33218 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
33219 "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
33220 "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
33221 var interact = function (e) {
33222 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
33225 onmousedown: interact,
33227 color: this._colorToCss(this._tag.textColor),
33228 transform: transform,
33230 textContent: this._tag.text,
33232 vNodes.push(vd.h("span.TagSymbol", properties, []));
33235 if (!this._tag.editable) {
33238 var lineColor = this._colorToCss(this._tag.lineColor);
33239 if (this._tag.geometry instanceof Component_1.RectGeometry) {
33240 var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
33241 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
33242 if (centroidCanvas != null) {
33243 var interact = this._interact(Component_1.TagOperation.Centroid, "move");
33244 var centroidCanvasX = Math.round(centroidCanvas[0]);
33245 var centroidCanvasY = Math.round(centroidCanvas[1]);
33246 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
33248 onmousedown: interact,
33249 style: { background: lineColor, transform: transform },
33251 vNodes.push(vd.h("div.TagMover", properties, []));
33254 var vertices2d = this._tag.geometry.getVertices2d();
33255 for (var i = 0; i < vertices2d.length - 1; i++) {
33257 ((this._tag.icon != null && i === this._tag.iconIndex) ||
33258 (this._tag.icon == null && this._tag.text != null && i === 3))) {
33261 var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
33262 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
33263 if (vertexCanvas == null) {
33266 var cursor = isRect ?
33267 i % 2 === 0 ? "nesw-resize" : "nwse-resize" :
33269 var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
33270 var vertexCanvasX = Math.round(vertexCanvas[0]);
33271 var vertexCanvasY = Math.round(vertexCanvas[1]);
33272 var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
33274 onmousedown: interact,
33275 style: { background: lineColor, transform: transform, cursor: cursor },
33277 vNodes.push(vd.h("div.TagResizer", properties, []));
33278 if (!this._tag.indicateVertices) {
33281 var pointProperties = {
33282 style: { background: lineColor, transform: transform },
33284 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
33288 OutlineRenderTag.prototype.getGLObjects = function () {
33289 var glObjects = [];
33290 if (this._fill != null) {
33291 glObjects.push(this._fill);
33293 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
33295 glObjects.push(hole);
33297 if (this._outline != null) {
33298 glObjects.push(this._outline);
33302 OutlineRenderTag.prototype.getRetrievableObjects = function () {
33303 return this._fill != null ? [this._fill] : [];
33305 OutlineRenderTag.prototype._colorToCss = function (color) {
33306 return "#" + ("000000" + color.toString(16)).substr(-6);
33308 OutlineRenderTag.prototype._createFill = function () {
33309 var triangles = this._tag.geometry.getTriangles3d(this._transform);
33310 var positions = new Float32Array(triangles);
33311 var geometry = new THREE.BufferGeometry();
33312 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33313 geometry.computeBoundingSphere();
33314 var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
33315 this._updateFillMaterial(material);
33316 return new THREE.Mesh(geometry, material);
33318 OutlineRenderTag.prototype._createHoles = function () {
33320 if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
33321 var polygonGeometry = this._tag.geometry;
33322 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
33323 for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
33324 var holePoints3d = holes3d_1[_i];
33325 var hole = this._createLine(holePoints3d);
33331 OutlineRenderTag.prototype._createLine = function (points3d) {
33332 var positions = this._getLinePositions(points3d);
33333 var geometry = new THREE.BufferGeometry();
33334 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33335 geometry.computeBoundingSphere();
33336 var material = new THREE.LineBasicMaterial();
33337 this._updateLineBasicMaterial(material);
33338 var line = new THREE.Line(geometry, material);
33339 line.renderOrder = 1;
33342 OutlineRenderTag.prototype._createOutline = function () {
33343 var points3d = this._tag.geometry.getPoints3d(this._transform);
33344 return this._createLine(points3d);
33346 OutlineRenderTag.prototype._disposeFill = function () {
33347 if (this._fill == null) {
33350 this._fill.geometry.dispose();
33351 this._fill.material.dispose();
33354 OutlineRenderTag.prototype._disposeHoles = function () {
33355 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
33357 hole.geometry.dispose();
33358 hole.material.dispose();
33362 OutlineRenderTag.prototype._disposeOutline = function () {
33363 if (this._outline == null) {
33366 this._outline.geometry.dispose();
33367 this._outline.material.dispose();
33368 this._outline = null;
33370 OutlineRenderTag.prototype._getLinePositions = function (points3d) {
33371 var length = points3d.length;
33372 var positions = new Float32Array(length * 3);
33373 for (var i = 0; i < length; ++i) {
33375 var position = points3d[i];
33376 positions[index + 0] = position[0];
33377 positions[index + 1] = position[1];
33378 positions[index + 2] = position[2];
33382 OutlineRenderTag.prototype._interact = function (operation, cursor, vertexIndex) {
33384 return function (e) {
33385 var offsetX = e.offsetX - e.target.offsetWidth / 2;
33386 var offsetY = e.offsetY - e.target.offsetHeight / 2;
33387 _this._interact$.next({
33391 operation: operation,
33393 vertexIndex: vertexIndex,
33397 OutlineRenderTag.prototype._updateFillGeometry = function () {
33398 var triangles = this._tag.geometry.getTriangles3d(this._transform);
33399 var positions = new Float32Array(triangles);
33400 var geometry = this._fill.geometry;
33401 var attribute = geometry.getAttribute("position");
33402 if (attribute.array.length === positions.length) {
33403 attribute.set(positions);
33404 attribute.needsUpdate = true;
33407 geometry.removeAttribute("position");
33408 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33410 geometry.computeBoundingSphere();
33412 OutlineRenderTag.prototype._updateFillMaterial = function (material) {
33413 material.color = new THREE.Color(this._tag.fillColor);
33414 material.opacity = this._tag.fillOpacity;
33415 material.needsUpdate = true;
33417 OutlineRenderTag.prototype._updateHoleGeometries = function () {
33418 var polygonGeometry = this._tag.geometry;
33419 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
33420 if (holes3d.length !== this._holes.length) {
33421 throw new Error("Changing the number of holes is not supported.");
33423 for (var i = 0; i < this._holes.length; i++) {
33424 var holePoints3d = holes3d[i];
33425 var hole = this._holes[i];
33426 this._updateLine(hole, holePoints3d);
33429 OutlineRenderTag.prototype._updateHoleMaterials = function () {
33430 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
33432 var material = hole.material;
33433 this._updateLineBasicMaterial(material);
33436 OutlineRenderTag.prototype._updateLine = function (line, points3d) {
33437 var positions = this._getLinePositions(points3d);
33438 var geometry = line.geometry;
33439 var attribute = geometry.getAttribute("position");
33440 attribute.set(positions);
33441 attribute.needsUpdate = true;
33442 geometry.computeBoundingSphere();
33444 OutlineRenderTag.prototype._updateOulineGeometry = function () {
33445 var points3d = this._tag.geometry.getPoints3d(this._transform);
33446 this._updateLine(this._outline, points3d);
33448 OutlineRenderTag.prototype._updateOutlineMaterial = function () {
33449 var material = this._outline.material;
33450 this._updateLineBasicMaterial(material);
33452 OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
33453 material.color = new THREE.Color(this._tag.lineColor);
33454 material.linewidth = Math.max(this._tag.lineWidth, 1);
33455 material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
33456 material.opacity = this._tag.lineOpacity;
33457 material.transparent = this._tag.lineOpacity < 1;
33458 material.needsUpdate = true;
33460 return OutlineRenderTag;
33461 }(Component_1.RenderTag));
33462 exports.OutlineRenderTag = OutlineRenderTag;
33464 },{"../../../Component":281,"three":231,"virtual-dom":237}],368:[function(require,module,exports){
33466 var __extends = (this && this.__extends) || (function () {
33467 var extendStatics = Object.setPrototypeOf ||
33468 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33469 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33470 return function (d, b) {
33471 extendStatics(d, b);
33472 function __() { this.constructor = d; }
33473 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33476 Object.defineProperty(exports, "__esModule", { value: true });
33477 var Subject_1 = require("rxjs/Subject");
33478 var Component_1 = require("../../../Component");
33479 var Viewer_1 = require("../../../Viewer");
33481 * @class OutlineTag
33483 * @classdesc Tag holding properties for visualizing a geometry outline.
33487 * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
33488 * var tag = new Mapillary.TagComponent.OutlineTag(
33491 * { editable: true, lineColor: 0xff0000 });
33493 * tagComponent.add([tag]);
33496 var OutlineTag = /** @class */ (function (_super) {
33497 __extends(OutlineTag, _super);
33499 * Create an outline tag.
33503 * @param {string} id - Unique identifier of the tag.
33504 * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
33505 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
33506 * behavior of the outline tag.
33508 function OutlineTag(id, geometry, options) {
33509 var _this = _super.call(this, id, geometry) || this;
33510 options = !!options ? options : {};
33511 _this._editable = options.editable == null ? false : options.editable;
33512 _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
33513 _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
33514 _this._icon = options.icon === undefined ? null : options.icon;
33515 _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
33516 _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
33517 _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
33518 _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
33519 _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
33520 _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
33521 _this._text = options.text === undefined ? null : options.text;
33522 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
33523 _this._click$ = new Subject_1.Subject();
33525 .subscribe(function (t) {
33526 _this.fire(OutlineTag.click, _this);
33530 Object.defineProperty(OutlineTag.prototype, "click$", {
33532 * Click observable.
33534 * @description An observable emitting the tag when the icon of the
33535 * tag has been clicked.
33537 * @returns {Observable<Tag>}
33540 return this._click$;
33545 Object.defineProperty(OutlineTag.prototype, "editable", {
33547 * Get editable property.
33548 * @returns {boolean} Value indicating if tag is editable.
33551 return this._editable;
33554 * Set editable property.
33557 * @fires Tag#changed
33559 set: function (value) {
33560 this._editable = value;
33561 this._notifyChanged$.next(this);
33566 Object.defineProperty(OutlineTag.prototype, "fillColor", {
33568 * Get fill color property.
33569 * @returns {number}
33572 return this._fillColor;
33575 * Set fill color property.
33578 * @fires Tag#changed
33580 set: function (value) {
33581 this._fillColor = value;
33582 this._notifyChanged$.next(this);
33587 Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
33589 * Get fill opacity property.
33590 * @returns {number}
33593 return this._fillOpacity;
33596 * Set fill opacity property.
33599 * @fires Tag#changed
33601 set: function (value) {
33602 this._fillOpacity = value;
33603 this._notifyChanged$.next(this);
33608 Object.defineProperty(OutlineTag.prototype, "geometry", {
33611 return this._geometry;
33616 Object.defineProperty(OutlineTag.prototype, "icon", {
33618 * Get icon property.
33619 * @returns {string}
33625 * Set icon property.
33628 * @fires Tag#changed
33630 set: function (value) {
33631 this._icon = value;
33632 this._notifyChanged$.next(this);
33637 Object.defineProperty(OutlineTag.prototype, "iconFloat", {
33639 * Get icon float property.
33640 * @returns {Alignment}
33643 return this._iconFloat;
33646 * Set icon float property.
33647 * @param {Alignment}
33649 * @fires Tag#changed
33651 set: function (value) {
33652 this._iconFloat = value;
33653 this._notifyChanged$.next(this);
33658 Object.defineProperty(OutlineTag.prototype, "iconIndex", {
33660 * Get icon index property.
33661 * @returns {number}
33664 return this._iconIndex;
33667 * Set icon index property.
33670 * @fires Tag#changed
33672 set: function (value) {
33673 this._iconIndex = value;
33674 this._notifyChanged$.next(this);
33679 Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
33681 * Get indicate vertices property.
33682 * @returns {boolean} Value indicating if vertices should be indicated
33683 * when tag is editable.
33686 return this._indicateVertices;
33689 * Set indicate vertices property.
33692 * @fires Tag#changed
33694 set: function (value) {
33695 this._indicateVertices = value;
33696 this._notifyChanged$.next(this);
33701 Object.defineProperty(OutlineTag.prototype, "lineColor", {
33703 * Get line color property.
33704 * @returns {number}
33707 return this._lineColor;
33710 * Set line color property.
33713 * @fires Tag#changed
33715 set: function (value) {
33716 this._lineColor = value;
33717 this._notifyChanged$.next(this);
33722 Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
33724 * Get line opacity property.
33725 * @returns {number}
33728 return this._lineOpacity;
33731 * Set line opacity property.
33734 * @fires Tag#changed
33736 set: function (value) {
33737 this._lineOpacity = value;
33738 this._notifyChanged$.next(this);
33743 Object.defineProperty(OutlineTag.prototype, "lineWidth", {
33745 * Get line width property.
33746 * @returns {number}
33749 return this._lineWidth;
33752 * Set line width property.
33755 * @fires Tag#changed
33757 set: function (value) {
33758 this._lineWidth = value;
33759 this._notifyChanged$.next(this);
33764 Object.defineProperty(OutlineTag.prototype, "text", {
33766 * Get text property.
33767 * @returns {string}
33773 * Set text property.
33776 * @fires Tag#changed
33778 set: function (value) {
33779 this._text = value;
33780 this._notifyChanged$.next(this);
33785 Object.defineProperty(OutlineTag.prototype, "textColor", {
33787 * Get text color property.
33788 * @returns {number}
33791 return this._textColor;
33794 * Set text color property.
33797 * @fires Tag#changed
33799 set: function (value) {
33800 this._textColor = value;
33801 this._notifyChanged$.next(this);
33807 * Set options for tag.
33809 * @description Sets all the option properties provided and keeps
33810 * the rest of the values as is.
33812 * @param {IOutlineTagOptions} options - Outline tag options
33814 * @fires {Tag#changed}
33816 OutlineTag.prototype.setOptions = function (options) {
33817 this._editable = options.editable == null ? this._editable : options.editable;
33818 this._icon = options.icon === undefined ? this._icon : options.icon;
33819 this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
33820 this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
33821 this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
33822 this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
33823 this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
33824 this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
33825 this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
33826 this._text = options.text === undefined ? this._text : options.text;
33827 this._textColor = options.textColor == null ? this._textColor : options.textColor;
33828 this._notifyChanged$.next(this);
33831 * Event fired when the icon of the outline tag is clicked.
33833 * @event OutlineTag#click
33834 * @type {OutlineTag} The tag instance that was clicked.
33836 OutlineTag.click = "click";
33838 }(Component_1.Tag));
33839 exports.OutlineTag = OutlineTag;
33840 exports.default = OutlineTag;
33842 },{"../../../Component":281,"../../../Viewer":292,"rxjs/Subject":34}],369:[function(require,module,exports){
33844 /// <reference path="../../../../typings/index.d.ts" />
33845 Object.defineProperty(exports, "__esModule", { value: true });
33846 var Subject_1 = require("rxjs/Subject");
33847 var Geo_1 = require("../../../Geo");
33848 var RenderTag = /** @class */ (function () {
33849 function RenderTag(tag, transform, viewportCoords) {
33851 this._transform = transform;
33852 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
33853 this._glObjectsChanged$ = new Subject_1.Subject();
33854 this._interact$ = new Subject_1.Subject();
33856 Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
33858 return this._glObjectsChanged$;
33863 Object.defineProperty(RenderTag.prototype, "interact$", {
33865 return this._interact$;
33870 Object.defineProperty(RenderTag.prototype, "tag", {
33879 exports.RenderTag = RenderTag;
33880 exports.default = RenderTag;
33882 },{"../../../Geo":284,"rxjs/Subject":34}],370:[function(require,module,exports){
33884 /// <reference path="../../../../typings/index.d.ts" />
33885 var __extends = (this && this.__extends) || (function () {
33886 var extendStatics = Object.setPrototypeOf ||
33887 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33888 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33889 return function (d, b) {
33890 extendStatics(d, b);
33891 function __() { this.constructor = d; }
33892 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33895 Object.defineProperty(exports, "__esModule", { value: true });
33896 var vd = require("virtual-dom");
33897 var Component_1 = require("../../../Component");
33898 var Viewer_1 = require("../../../Viewer");
33900 * @class SpotRenderTag
33901 * @classdesc Tag visualizing the properties of a SpotTag.
33903 var SpotRenderTag = /** @class */ (function (_super) {
33904 __extends(SpotRenderTag, _super);
33905 function SpotRenderTag() {
33906 return _super !== null && _super.apply(this, arguments) || this;
33908 SpotRenderTag.prototype.dispose = function () { };
33909 SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
33911 var tag = this._tag;
33913 offsetHeight: size.height, offsetWidth: size.width,
33916 var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
33917 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
33918 if (centroidCanvas != null) {
33919 var interactNone = function (e) {
33920 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
33922 var canvasX = Math.round(centroidCanvas[0]);
33923 var canvasY = Math.round(centroidCanvas[1]);
33924 if (tag.icon != null) {
33925 if (atlas.loaded) {
33926 var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
33927 var iconTransform = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
33929 onmousedown: interactNone,
33931 pointerEvents: "all",
33932 transform: iconTransform,
33935 vNodes.push(vd.h("div", properties, [sprite]));
33938 else if (tag.text != null) {
33939 var textTransform = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
33941 onmousedown: interactNone,
33943 color: this._colorToCss(tag.textColor),
33944 transform: textTransform,
33946 textContent: tag.text,
33948 vNodes.push(vd.h("span.TagSymbol", properties, []));
33950 var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move");
33951 var background = this._colorToCss(tag.color);
33952 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
33953 if (tag.editable) {
33954 var interactorProperties = {
33955 onmousedown: interact,
33957 background: background,
33958 transform: transform,
33961 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
33963 var pointProperties = {
33965 background: background,
33966 transform: transform,
33969 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
33973 SpotRenderTag.prototype.getGLObjects = function () { return []; };
33974 SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
33975 SpotRenderTag.prototype._colorToCss = function (color) {
33976 return "#" + ("000000" + color.toString(16)).substr(-6);
33978 SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) {
33980 return function (e) {
33981 var offsetX = e.offsetX - e.target.offsetWidth / 2;
33982 var offsetY = e.offsetY - e.target.offsetHeight / 2;
33983 _this._interact$.next({
33987 operation: operation,
33989 vertexIndex: vertexIndex,
33993 return SpotRenderTag;
33994 }(Component_1.RenderTag));
33995 exports.SpotRenderTag = SpotRenderTag;
33997 },{"../../../Component":281,"../../../Viewer":292,"virtual-dom":237}],371:[function(require,module,exports){
33999 var __extends = (this && this.__extends) || (function () {
34000 var extendStatics = Object.setPrototypeOf ||
34001 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34002 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34003 return function (d, b) {
34004 extendStatics(d, b);
34005 function __() { this.constructor = d; }
34006 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34009 Object.defineProperty(exports, "__esModule", { value: true });
34010 var Component_1 = require("../../../Component");
34014 * @classdesc Tag holding properties for visualizing the centroid of a geometry.
34018 * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
34019 * var tag = new Mapillary.TagComponent.SpotTag(
34022 * { editable: true, color: 0xff0000 });
34024 * tagComponent.add([tag]);
34027 var SpotTag = /** @class */ (function (_super) {
34028 __extends(SpotTag, _super);
34030 * Create a spot tag.
34034 * @param {string} id
34035 * @param {Geometry} geometry
34036 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
34037 * behavior of the spot tag.
34039 function SpotTag(id, geometry, options) {
34040 var _this = _super.call(this, id, geometry) || this;
34041 options = !!options ? options : {};
34042 _this._color = options.color == null ? 0xFFFFFF : options.color;
34043 _this._editable = options.editable == null ? false : options.editable;
34044 _this._icon = options.icon === undefined ? null : options.icon;
34045 _this._text = options.text === undefined ? null : options.text;
34046 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
34049 Object.defineProperty(SpotTag.prototype, "color", {
34051 * Get color property.
34052 * @returns {number} The color of the spot as a hexagonal number;
34055 return this._color;
34058 * Set color property.
34061 * @fires Tag#changed
34063 set: function (value) {
34064 this._color = value;
34065 this._notifyChanged$.next(this);
34070 Object.defineProperty(SpotTag.prototype, "editable", {
34072 * Get editable property.
34073 * @returns {boolean} Value indicating if tag is editable.
34076 return this._editable;
34079 * Set editable property.
34082 * @fires Tag#changed
34084 set: function (value) {
34085 this._editable = value;
34086 this._notifyChanged$.next(this);
34091 Object.defineProperty(SpotTag.prototype, "icon", {
34093 * Get icon property.
34094 * @returns {string}
34100 * Set icon property.
34103 * @fires Tag#changed
34105 set: function (value) {
34106 this._icon = value;
34107 this._notifyChanged$.next(this);
34112 Object.defineProperty(SpotTag.prototype, "text", {
34114 * Get text property.
34115 * @returns {string}
34121 * Set text property.
34124 * @fires Tag#changed
34126 set: function (value) {
34127 this._text = value;
34128 this._notifyChanged$.next(this);
34133 Object.defineProperty(SpotTag.prototype, "textColor", {
34135 * Get text color property.
34136 * @returns {number}
34139 return this._textColor;
34142 * Set text color property.
34145 * @fires Tag#changed
34147 set: function (value) {
34148 this._textColor = value;
34149 this._notifyChanged$.next(this);
34155 * Set options for tag.
34157 * @description Sets all the option properties provided and keps
34158 * the rest of the values as is.
34160 * @param {ISpotTagOptions} options - Spot tag options
34162 * @fires {Tag#changed}
34164 SpotTag.prototype.setOptions = function (options) {
34165 this._color = options.color == null ? this._color : options.color;
34166 this._editable = options.editable == null ? this._editable : options.editable;
34167 this._icon = options.icon === undefined ? this._icon : options.icon;
34168 this._text = options.text === undefined ? this._text : options.text;
34169 this._textColor = options.textColor == null ? this._textColor : options.textColor;
34170 this._notifyChanged$.next(this);
34173 }(Component_1.Tag));
34174 exports.SpotTag = SpotTag;
34175 exports.default = SpotTag;
34177 },{"../../../Component":281}],372:[function(require,module,exports){
34179 var __extends = (this && this.__extends) || (function () {
34180 var extendStatics = Object.setPrototypeOf ||
34181 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34182 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34183 return function (d, b) {
34184 extendStatics(d, b);
34185 function __() { this.constructor = d; }
34186 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34189 Object.defineProperty(exports, "__esModule", { value: true });
34190 var Subject_1 = require("rxjs/Subject");
34191 require("rxjs/add/operator/map");
34192 require("rxjs/add/operator/share");
34193 var Utils_1 = require("../../../Utils");
34197 * @classdesc Abstract class representing the basic functionality of for a tag.
34199 var Tag = /** @class */ (function (_super) {
34200 __extends(Tag, _super);
34205 * @param {string} id
34206 * @param {Geometry} geometry
34208 function Tag(id, geometry) {
34209 var _this = _super.call(this) || this;
34211 _this._geometry = geometry;
34212 _this._notifyChanged$ = new Subject_1.Subject();
34213 _this._notifyChanged$
34214 .subscribe(function (t) {
34215 _this.fire(Tag.changed, _this);
34217 _this._geometry.changed$
34218 .subscribe(function (g) {
34219 _this.fire(Tag.geometrychanged, _this);
34223 Object.defineProperty(Tag.prototype, "id", {
34226 * @returns {string}
34234 Object.defineProperty(Tag.prototype, "geometry", {
34236 * Get geometry property.
34237 * @returns {Geometry} The geometry of the tag.
34240 return this._geometry;
34245 Object.defineProperty(Tag.prototype, "changed$", {
34247 * Get changed observable.
34248 * @returns {Observable<Tag>}
34252 return this._notifyChanged$;
34257 Object.defineProperty(Tag.prototype, "geometryChanged$", {
34259 * Get geometry changed observable.
34260 * @returns {Observable<Tag>}
34265 return this._geometry.changed$
34266 .map(function (geometry) {
34275 * Event fired when a property related to the visual appearance of the
34278 * @event Tag#changed
34279 * @type {Tag} The tag instance that has changed.
34281 Tag.changed = "changed";
34283 * Event fired when the geometry of the tag has changed.
34285 * @event Tag#geometrychanged
34286 * @type {Tag} The tag instance whose geometry has changed.
34288 Tag.geometrychanged = "geometrychanged";
34290 }(Utils_1.EventEmitter));
34292 exports.default = Tag;
34294 },{"../../../Utils":291,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/share":76}],373:[function(require,module,exports){
34296 Object.defineProperty(exports, "__esModule", { value: true });
34297 var HandlerBase = /** @class */ (function () {
34298 function HandlerBase(component, container, navigator) {
34299 this._component = component;
34300 this._container = container;
34301 this._navigator = navigator;
34302 this._enabled = false;
34304 Object.defineProperty(HandlerBase.prototype, "isEnabled", {
34306 * Returns a Boolean indicating whether the interaction is enabled.
34308 * @returns {boolean} `true` if the interaction is enabled.
34311 return this._enabled;
34317 * Enables the interaction.
34319 * @example ```<component-name>.<handler-name>.enable();```
34321 HandlerBase.prototype.enable = function () {
34322 if (this._enabled || !this._component.activated) {
34326 this._enabled = true;
34327 this._component.configure(this._getConfiguration(true));
34330 * Disables the interaction.
34332 * @example ```<component-name>.<handler-name>.disable();```
34334 HandlerBase.prototype.disable = function () {
34335 if (!this._enabled) {
34339 this._enabled = false;
34340 if (this._component.activated) {
34341 this._component.configure(this._getConfiguration(false));
34344 return HandlerBase;
34346 exports.HandlerBase = HandlerBase;
34347 exports.default = HandlerBase;
34349 },{}],374:[function(require,module,exports){
34351 var __extends = (this && this.__extends) || (function () {
34352 var extendStatics = Object.setPrototypeOf ||
34353 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34354 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34355 return function (d, b) {
34356 extendStatics(d, b);
34357 function __() { this.constructor = d; }
34358 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34361 Object.defineProperty(exports, "__esModule", { value: true });
34362 var MapillaryError_1 = require("./MapillaryError");
34363 var ArgumentMapillaryError = /** @class */ (function (_super) {
34364 __extends(ArgumentMapillaryError, _super);
34365 function ArgumentMapillaryError(message) {
34366 var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
34367 _this.name = "ArgumentMapillaryError";
34370 return ArgumentMapillaryError;
34371 }(MapillaryError_1.MapillaryError));
34372 exports.ArgumentMapillaryError = ArgumentMapillaryError;
34373 exports.default = ArgumentMapillaryError;
34375 },{"./MapillaryError":376}],375:[function(require,module,exports){
34377 var __extends = (this && this.__extends) || (function () {
34378 var extendStatics = Object.setPrototypeOf ||
34379 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34380 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34381 return function (d, b) {
34382 extendStatics(d, b);
34383 function __() { this.constructor = d; }
34384 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34387 Object.defineProperty(exports, "__esModule", { value: true });
34388 var MapillaryError_1 = require("./MapillaryError");
34389 var GraphMapillaryError = /** @class */ (function (_super) {
34390 __extends(GraphMapillaryError, _super);
34391 function GraphMapillaryError(message) {
34392 var _this = _super.call(this, message) || this;
34393 _this.name = "GraphMapillaryError";
34396 return GraphMapillaryError;
34397 }(MapillaryError_1.MapillaryError));
34398 exports.GraphMapillaryError = GraphMapillaryError;
34399 exports.default = GraphMapillaryError;
34401 },{"./MapillaryError":376}],376:[function(require,module,exports){
34403 var __extends = (this && this.__extends) || (function () {
34404 var extendStatics = Object.setPrototypeOf ||
34405 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34406 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34407 return function (d, b) {
34408 extendStatics(d, b);
34409 function __() { this.constructor = d; }
34410 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34413 Object.defineProperty(exports, "__esModule", { value: true });
34414 var MapillaryError = /** @class */ (function (_super) {
34415 __extends(MapillaryError, _super);
34416 function MapillaryError(message) {
34417 var _this = _super.call(this, message) || this;
34418 _this.name = "MapillaryError";
34421 return MapillaryError;
34423 exports.MapillaryError = MapillaryError;
34424 exports.default = MapillaryError;
34426 },{}],377:[function(require,module,exports){
34428 /// <reference path="../../typings/index.d.ts" />
34429 Object.defineProperty(exports, "__esModule", { value: true });
34430 var THREE = require("three");
34434 * @classdesc Holds information about a camera.
34436 var Camera = /** @class */ (function () {
34438 * Create a new camera instance.
34439 * @param {Transform} [transform] - Optional transform instance.
34441 function Camera(transform) {
34442 if (transform != null) {
34443 this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
34444 this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
34445 this._up = transform.upVector();
34446 this._focal = this._getFocal(transform);
34449 this._position = new THREE.Vector3(0, 0, 0);
34450 this._lookat = new THREE.Vector3(0, 0, 1);
34451 this._up = new THREE.Vector3(0, -1, 0);
34455 Object.defineProperty(Camera.prototype, "position", {
34458 * @returns {THREE.Vector3} The position vector.
34461 return this._position;
34466 Object.defineProperty(Camera.prototype, "lookat", {
34469 * @returns {THREE.Vector3} The lookat vector.
34472 return this._lookat;
34477 Object.defineProperty(Camera.prototype, "up", {
34480 * @returns {THREE.Vector3} The up vector.
34488 Object.defineProperty(Camera.prototype, "focal", {
34491 * @returns {number} The focal length.
34494 return this._focal;
34499 set: function (value) {
34500 this._focal = value;
34506 * Update this camera to the linearly interpolated value of two other cameras.
34508 * @param {Camera} a - First camera.
34509 * @param {Camera} b - Second camera.
34510 * @param {number} alpha - Interpolation value on the interval [0, 1].
34512 Camera.prototype.lerpCameras = function (a, b, alpha) {
34513 this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
34514 this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
34515 this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
34516 this._focal = (1 - alpha) * a.focal + alpha * b.focal;
34519 * Copy the properties of another camera to this camera.
34521 * @param {Camera} other - Another camera.
34523 Camera.prototype.copy = function (other) {
34524 this._position.copy(other.position);
34525 this._lookat.copy(other.lookat);
34526 this._up.copy(other.up);
34527 this._focal = other.focal;
34530 * Clone this camera.
34532 * @returns {Camera} A camera with cloned properties equal to this camera.
34534 Camera.prototype.clone = function () {
34535 var camera = new Camera();
34536 camera.position.copy(this._position);
34537 camera.lookat.copy(this._lookat);
34538 camera.up.copy(this._up);
34539 camera.focal = this._focal;
34543 * Determine the distance between this camera and another camera.
34545 * @param {Camera} other - Another camera.
34546 * @returns {number} The distance between the cameras.
34548 Camera.prototype.diff = function (other) {
34549 var pd = this._position.distanceToSquared(other.position);
34550 var ld = this._lookat.distanceToSquared(other.lookat);
34551 var ud = this._up.distanceToSquared(other.up);
34552 var fd = 100 * Math.abs(this._focal - other.focal);
34553 return Math.max(pd, ld, ud, fd);
34556 * Get the focal length based on the transform.
34558 * @description Returns the focal length of the transform if gpano info is not available.
34559 * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
34560 * the gpano information if available.
34562 * @returns {number} Focal length.
34564 Camera.prototype._getFocal = function (transform) {
34565 if (transform.gpano == null) {
34566 return transform.focal;
34568 var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
34569 var focal = 0.5 / Math.tan(vFov / 2);
34570 return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
34574 exports.Camera = Camera;
34576 },{"three":231}],378:[function(require,module,exports){
34578 Object.defineProperty(exports, "__esModule", { value: true });
34582 * @classdesc Converts coordinates between the geodetic (WGS84),
34583 * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
34584 * East, North, Up (ENU) reference frames.
34586 * The WGS84 has latitude (degrees), longitude (degrees) and
34587 * altitude (meters) values.
34589 * The ECEF Z-axis pierces the north pole and the
34590 * XY-axis defines the equatorial plane. The X-axis extends
34591 * from the geocenter to the intersection of the Equator and
34592 * the Greenwich Meridian. All values in meters.
34594 * The WGS84 parameters are:
34598 * f = 1 / 298.257223563
34599 * e = Math.sqrt((a^2 - b^2) / a^2)
34600 * e' = Math.sqrt((a^2 - b^2) / b^2)
34602 * The WGS84 to ECEF conversion is performed using the following:
34604 * X = (N - h) * cos(phi) * cos(lambda)
34605 * Y = (N + h) * cos(phi) * sin(lambda)
34606 * Z = (b^2 * N / a^2 + h) * sin(phi)
34611 * lambda = longitude
34612 * h = height above ellipsoid (altitude)
34613 * N = Radius of curvature (meters)
34614 * = a / Math.sqrt(1 - e^2 * sin(phi)^2)
34616 * The ECEF to WGS84 conversion is performed using the following:
34618 * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
34619 * lambda = arctan(Y / X)
34620 * h = p / cos(phi) - N
34624 * p = Math.sqrt(X^2 + Y^2)
34625 * theta = arctan(Z * a / p * b)
34627 * In the ENU reference frame the x-axis points to the
34628 * East, the y-axis to the North and the z-axis Up. All values
34631 * The ECEF to ENU conversion is performed using the following:
34633 * | x | | -sin(lambda_r) cos(lambda_r) 0 | | X - X_r |
34634 * | y | = | -sin(phi_r) * cos(lambda_r) -sin(phi_r) * sin(lambda_r) cos(phi_r) | | Y - Y_r |
34635 * | z | | cos(phi_r) * cos(lambda_r) cos(phi_r) * sin(lambda_r) sin(phi_r) | | Z - Z_r |
34639 * phi_r = latitude of reference
34640 * lambda_r = longitude of reference
34641 * X_r, Y_r, Z_r = ECEF coordinates of reference
34643 * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
34645 * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
34646 * the first step for both conversions.
34648 var GeoCoords = /** @class */ (function () {
34649 function GeoCoords() {
34650 this._wgs84a = 6378137.0;
34651 this._wgs84b = 6356752.31424518;
34654 * Convert coordinates from geodetic (WGS84) reference to local topocentric
34657 * @param {number} lat Latitude in degrees.
34658 * @param {number} lon Longitude in degrees.
34659 * @param {number} alt Altitude in meters.
34660 * @param {number} refLat Reference latitude in degrees.
34661 * @param {number} refLon Reference longitude in degrees.
34662 * @param {number} refAlt Reference altitude in meters.
34663 * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
34665 GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
34666 var ecef = this.geodeticToEcef(lat, lon, alt);
34667 return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
34670 * Convert coordinates from local topocentric (ENU) reference to
34671 * geodetic (WGS84) reference.
34673 * @param {number} x Topocentric ENU coordinate in East direction.
34674 * @param {number} y Topocentric ENU coordinate in North direction.
34675 * @param {number} z Topocentric ENU coordinate in Up direction.
34676 * @param {number} refLat Reference latitude in degrees.
34677 * @param {number} refLon Reference longitude in degrees.
34678 * @param {number} refAlt Reference altitude in meters.
34679 * @returns {Array<number>} The latitude and longitude in degrees
34680 * as well as altitude in meters.
34682 GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
34683 var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
34684 return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
34687 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
34688 * to local topocentric (ENU) reference.
34690 * @param {number} X ECEF X-value.
34691 * @param {number} Y ECEF Y-value.
34692 * @param {number} Z ECEF Z-value.
34693 * @param {number} refLat Reference latitude in degrees.
34694 * @param {number} refLon Reference longitude in degrees.
34695 * @param {number} refAlt Reference altitude in meters.
34696 * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
34697 * and Up directions respectively.
34699 GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
34700 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
34701 var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
34702 refLat = refLat * Math.PI / 180.0;
34703 refLon = refLon * Math.PI / 180.0;
34704 var cosLat = Math.cos(refLat);
34705 var sinLat = Math.sin(refLat);
34706 var cosLon = Math.cos(refLon);
34707 var sinLon = Math.sin(refLon);
34708 var x = -sinLon * V[0] + cosLon * V[1];
34709 var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
34710 var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
34714 * Convert coordinates from local topocentric (ENU) reference
34715 * to Earth-Centered, Earth-Fixed (ECEF) reference.
34717 * @param {number} x Topocentric ENU coordinate in East direction.
34718 * @param {number} y Topocentric ENU coordinate in North direction.
34719 * @param {number} z Topocentric ENU coordinate in Up direction.
34720 * @param {number} refLat Reference latitude in degrees.
34721 * @param {number} refLon Reference longitude in degrees.
34722 * @param {number} refAlt Reference altitude in meters.
34723 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
34725 GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
34726 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
34727 refLat = refLat * Math.PI / 180.0;
34728 refLon = refLon * Math.PI / 180.0;
34729 var cosLat = Math.cos(refLat);
34730 var sinLat = Math.sin(refLat);
34731 var cosLon = Math.cos(refLon);
34732 var sinLon = Math.sin(refLon);
34733 var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
34734 var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
34735 var Z = cosLat * y + sinLat * z + refEcef[2];
34739 * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
34740 * Earth-Fixed (ECEF) reference.
34742 * @param {number} lat Latitude in degrees.
34743 * @param {number} lon Longitude in degrees.
34744 * @param {number} alt Altitude in meters.
34745 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
34747 GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
34748 var a = this._wgs84a;
34749 var b = this._wgs84b;
34750 lat = lat * Math.PI / 180.0;
34751 lon = lon * Math.PI / 180.0;
34752 var cosLat = Math.cos(lat);
34753 var sinLat = Math.sin(lat);
34754 var cosLon = Math.cos(lon);
34755 var sinLon = Math.sin(lon);
34758 var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
34759 var nhcl = (a2 * L + alt) * cosLat;
34760 var X = nhcl * cosLon;
34761 var Y = nhcl * sinLon;
34762 var Z = (b2 * L + alt) * sinLat;
34766 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
34767 * to geodetic reference (WGS84).
34769 * @param {number} X ECEF X-value.
34770 * @param {number} Y ECEF Y-value.
34771 * @param {number} Z ECEF Z-value.
34772 * @returns {Array<number>} The latitude and longitude in degrees
34773 * as well as altitude in meters.
34775 GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
34776 var a = this._wgs84a;
34777 var b = this._wgs84b;
34780 var a2mb2 = a2 - b2;
34781 var ea = Math.sqrt(a2mb2 / a2);
34782 var eb = Math.sqrt(a2mb2 / b2);
34783 var p = Math.sqrt(X * X + Y * Y);
34784 var theta = Math.atan2(Z * a, p * b);
34785 var sinTheta = Math.sin(theta);
34786 var cosTheta = Math.cos(theta);
34787 var lon = Math.atan2(Y, X);
34788 var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
34789 var sinLat = Math.sin(lat);
34790 var cosLat = Math.cos(lat);
34791 var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
34792 var alt = p / cosLat - N;
34793 return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
34797 exports.GeoCoords = GeoCoords;
34798 exports.default = GeoCoords;
34800 },{}],379:[function(require,module,exports){
34802 /// <reference path="../../typings/index.d.ts" />
34803 Object.defineProperty(exports, "__esModule", { value: true });
34804 var THREE = require("three");
34808 * @classdesc Provides methods for scalar, vector and matrix calculations.
34810 var Spatial = /** @class */ (function () {
34811 function Spatial() {
34812 this._epsilon = 1e-9;
34815 * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
34816 * bearing (clockwise with origin at north or Y-axis).
34818 * @param {number} phi - Azimuthal phi angle in radians.
34819 * @returns {number} Bearing in radians.
34821 Spatial.prototype.azimuthalToBearing = function (phi) {
34822 return -phi + Math.PI / 2;
34825 * Converts degrees to radians.
34827 * @param {number} deg - Degrees.
34828 * @returns {number} Radians.
34830 Spatial.prototype.degToRad = function (deg) {
34831 return Math.PI * deg / 180;
34834 * Converts radians to degrees.
34836 * @param {number} rad - Radians.
34837 * @returns {number} Degrees.
34839 Spatial.prototype.radToDeg = function (rad) {
34840 return 180 * rad / Math.PI;
34843 * Creates a rotation matrix from an angle-axis vector.
34845 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
34846 * @returns {THREE.Matrix4} Rotation matrix.
34848 Spatial.prototype.rotationMatrix = function (angleAxis) {
34849 var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
34850 var angle = axis.length();
34854 return new THREE.Matrix4().makeRotationAxis(axis, angle);
34857 * Rotates a vector according to a angle-axis rotation vector.
34859 * @param {Array<number>} vector - Vector to rotate.
34860 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
34861 * @returns {THREE.Vector3} Rotated vector.
34863 Spatial.prototype.rotate = function (vector, angleAxis) {
34864 var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
34865 var rotationMatrix = this.rotationMatrix(angleAxis);
34866 v.applyMatrix4(rotationMatrix);
34870 * Calculates the optical center from a rotation vector
34871 * on the angle-axis representation and a translation vector
34872 * according to C = -R^T t.
34874 * @param {Array<number>} rotation - Angle-axis representation of a rotation.
34875 * @param {Array<number>} translation - Translation vector.
34876 * @returns {THREE.Vector3} Optical center.
34878 Spatial.prototype.opticalCenter = function (rotation, translation) {
34879 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
34880 var vector = [-translation[0], -translation[1], -translation[2]];
34881 return this.rotate(vector, angleAxis);
34884 * Calculates the viewing direction from a rotation vector
34885 * on the angle-axis representation.
34887 * @param {number[]} rotation - Angle-axis representation of a rotation.
34888 * @returns {THREE.Vector3} Viewing direction.
34890 Spatial.prototype.viewingDirection = function (rotation) {
34891 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
34892 return this.rotate([0, 0, 1], angleAxis);
34895 * Wrap a number on the interval [min, max].
34897 * @param {number} value - Value to wrap.
34898 * @param {number} min - Lower endpoint of interval.
34899 * @param {number} max - Upper endpoint of interval.
34900 * @returns {number} The wrapped number.
34902 Spatial.prototype.wrap = function (value, min, max) {
34904 throw new Error("Invalid arguments: max must be larger than min.");
34906 var interval = (max - min);
34907 while (value > max || value < min) {
34909 value = value - interval;
34911 else if (value < min) {
34912 value = value + interval;
34918 * Wrap an angle on the interval [-Pi, Pi].
34920 * @param {number} angle - Value to wrap.
34921 * @returns {number} Wrapped angle.
34923 Spatial.prototype.wrapAngle = function (angle) {
34924 return this.wrap(angle, -Math.PI, Math.PI);
34927 * Limit the value to the interval [min, max] by changing the value to
34928 * the nearest available one when it is outside the interval.
34930 * @param {number} value - Value to clamp.
34931 * @param {number} min - Minimum of the interval.
34932 * @param {number} max - Maximum of the interval.
34933 * @returns {number} Clamped value.
34935 Spatial.prototype.clamp = function (value, min, max) {
34945 * Calculates the counter-clockwise angle from the first
34946 * vector (x1, y1)^T to the second (x2, y2)^T.
34948 * @param {number} x1 - X coordinate of first vector.
34949 * @param {number} y1 - Y coordinate of first vector.
34950 * @param {number} x2 - X coordinate of second vector.
34951 * @param {number} y2 - Y coordinate of second vector.
34952 * @returns {number} Counter clockwise angle between the vectors.
34954 Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
34955 var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
34956 return this.wrapAngle(angle);
34959 * Calculates the minimum (absolute) angle change for rotation
34960 * from one angle to another on the [-Pi, Pi] interval.
34962 * @param {number} angle1 - Start angle.
34963 * @param {number} angle2 - Destination angle.
34964 * @returns {number} Absolute angle change between angles.
34966 Spatial.prototype.angleDifference = function (angle1, angle2) {
34967 var angle = angle2 - angle1;
34968 return this.wrapAngle(angle);
34971 * Calculates the relative rotation angle between two
34972 * angle-axis vectors.
34974 * @param {number} rotation1 - First angle-axis vector.
34975 * @param {number} rotation2 - Second angle-axis vector.
34976 * @returns {number} Relative rotation angle.
34978 Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
34979 var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
34980 var R2 = this.rotationMatrix(rotation2);
34981 var R = R1T.multiply(R2);
34982 var elements = R.elements;
34983 // from Tr(R) = 1 + 2*cos(theta)
34984 var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
34988 * Calculates the angle from a vector to a plane.
34990 * @param {Array<number>} vector - The vector.
34991 * @param {Array<number>} planeNormal - Normal of the plane.
34992 * @returns {number} Angle from between plane and vector.
34994 Spatial.prototype.angleToPlane = function (vector, planeNormal) {
34995 var v = new THREE.Vector3().fromArray(vector);
34996 var norm = v.length();
34997 if (norm < this._epsilon) {
35000 var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
35001 return Math.asin(projection / norm);
35004 * Calculates the distance between two coordinates
35005 * (latitude longitude pairs) in meters according to
35006 * the haversine formula.
35008 * @param {number} lat1 - Latitude of the first coordinate.
35009 * @param {number} lon1 - Longitude of the first coordinate.
35010 * @param {number} lat2 - Latitude of the second coordinate.
35011 * @param {number} lon2 - Longitude of the second coordinate.
35012 * @returns {number} Distance between lat lon positions.
35014 Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
35016 var dLat = this.degToRad(lat2 - lat1);
35017 var dLon = this.degToRad(lon2 - lon1);
35018 var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
35019 Math.cos(lat1) * Math.cos(lat2) *
35020 Math.sin(dLon / 2) * Math.sin(dLon / 2);
35021 var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
35026 exports.Spatial = Spatial;
35027 exports.default = Spatial;
35029 },{"three":231}],380:[function(require,module,exports){
35031 /// <reference path="../../typings/index.d.ts" />
35032 Object.defineProperty(exports, "__esModule", { value: true });
35033 var THREE = require("three");
35037 * @classdesc Class used for calculating coordinate transformations
35040 var Transform = /** @class */ (function () {
35042 * Create a new transform instance.
35043 * @param {Node} apiNavImIm - Node properties.
35044 * @param {HTMLImageElement} image - Node image.
35045 * @param {Array<number>} translation - Node translation vector in three dimensions.
35047 function Transform(node, image, translation) {
35048 this._orientation = this._getValue(node.orientation, 1);
35049 var imageWidth = image != null ? image.width : 4;
35050 var imageHeight = image != null ? image.height : 3;
35051 var keepOrientation = this._orientation < 5;
35052 this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
35053 this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
35054 this._basicAspect = keepOrientation ?
35055 this._width / this._height :
35056 this._height / this._width;
35057 this._basicWidth = keepOrientation ? node.width : node.height;
35058 this._basicHeight = keepOrientation ? node.height : node.width;
35059 this._focal = this._getValue(node.focal, 1);
35060 this._scale = this._getValue(node.scale, 0);
35061 this._gpano = node.gpano != null ? node.gpano : null;
35062 this._rt = this._getRt(node.rotation, translation);
35063 this._srt = this._getSrt(this._rt, this._scale);
35065 Object.defineProperty(Transform.prototype, "basicAspect", {
35067 * Get basic aspect.
35068 * @returns {number} The orientation adjusted aspect ratio.
35071 return this._basicAspect;
35076 Object.defineProperty(Transform.prototype, "basicHeight", {
35078 * Get basic height.
35080 * @description Does not fall back to node image height but
35081 * uses original value from API so can be faulty.
35083 * @returns {number} The height of the basic version image
35084 * (adjusted for orientation).
35087 return this._basicHeight;
35092 Object.defineProperty(Transform.prototype, "basicWidth", {
35096 * @description Does not fall back to node image width but
35097 * uses original value from API so can be faulty.
35099 * @returns {number} The width of the basic version image
35100 * (adjusted for orientation).
35103 return this._basicWidth;
35108 Object.defineProperty(Transform.prototype, "focal", {
35111 * @returns {number} The node focal length.
35114 return this._focal;
35119 Object.defineProperty(Transform.prototype, "fullPano", {
35123 * @returns {boolean} Value indicating whether the node is a complete
35127 return this._gpano != null &&
35128 this._gpano.CroppedAreaLeftPixels === 0 &&
35129 this._gpano.CroppedAreaTopPixels === 0 &&
35130 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
35131 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
35136 Object.defineProperty(Transform.prototype, "gpano", {
35139 * @returns {number} The node gpano information.
35142 return this._gpano;
35147 Object.defineProperty(Transform.prototype, "height", {
35151 * @description Falls back to the node image height if
35152 * the API data is faulty.
35154 * @returns {number} The orientation adjusted image height.
35157 return this._height;
35162 Object.defineProperty(Transform.prototype, "orientation", {
35165 * @returns {number} The image orientation.
35168 return this._orientation;
35173 Object.defineProperty(Transform.prototype, "rt", {
35176 * @returns {THREE.Matrix4} The extrinsic camera matrix.
35184 Object.defineProperty(Transform.prototype, "srt", {
35187 * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
35195 Object.defineProperty(Transform.prototype, "scale", {
35198 * @returns {number} The node atomic reconstruction scale.
35201 return this._scale;
35206 Object.defineProperty(Transform.prototype, "hasValidScale", {
35208 * Get has valid scale.
35209 * @returns {boolean} Value indicating if the scale of the transform is valid.
35212 return this._scale > 1e-2 && this._scale < 50;
35217 Object.defineProperty(Transform.prototype, "width", {
35221 * @description Falls back to the node image width if
35222 * the API data is faulty.
35224 * @returns {number} The orientation adjusted image width.
35227 return this._width;
35233 * Calculate the up vector for the node transform.
35235 * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
35237 Transform.prototype.upVector = function () {
35238 var rte = this._rt.elements;
35239 switch (this._orientation) {
35241 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
35243 return new THREE.Vector3(rte[1], rte[5], rte[9]);
35245 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
35247 return new THREE.Vector3(rte[0], rte[4], rte[8]);
35249 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
35253 * Calculate projector matrix for projecting 3D points to texture map
35254 * coordinates (u and v).
35256 * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
35257 * map coordinate calculations.
35259 Transform.prototype.projectorMatrix = function () {
35260 var projector = this._normalizedToTextureMatrix();
35261 var f = this._focal;
35262 var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
35263 projector.multiply(projection);
35264 projector.multiply(this._rt);
35268 * Project 3D world coordinates to basic coordinates.
35270 * @param {Array<number>} point3d - 3D world coordinates.
35271 * @return {Array<number>} 2D basic coordinates.
35273 Transform.prototype.projectBasic = function (point3d) {
35274 var sfm = this.projectSfM(point3d);
35275 return this._sfmToBasic(sfm);
35278 * Unproject basic coordinates to 3D world coordinates.
35280 * @param {Array<number>} basic - 2D basic coordinates.
35281 * @param {Array<number>} distance - Depth to unproject from camera center.
35282 * @returns {Array<number>} Unprojected 3D world coordinates.
35284 Transform.prototype.unprojectBasic = function (basic, distance) {
35285 var sfm = this._basicToSfm(basic);
35286 return this.unprojectSfM(sfm, distance);
35289 * Project 3D world coordinates to SfM coordinates.
35291 * @param {Array<number>} point3d - 3D world coordinates.
35292 * @return {Array<number>} 2D SfM coordinates.
35294 Transform.prototype.projectSfM = function (point3d) {
35295 var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
35296 v.applyMatrix4(this._rt);
35297 return this._bearingToSfm([v.x, v.y, v.z]);
35300 * Unproject SfM coordinates to a 3D world coordinates.
35302 * @param {Array<number>} sfm - 2D SfM coordinates.
35303 * @param {Array<number>} distance - Depth to unproject from camera center.
35304 * @returns {Array<number>} Unprojected 3D world coordinates.
35306 Transform.prototype.unprojectSfM = function (sfm, distance) {
35307 var bearing = this._sfmToBearing(sfm);
35308 var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
35309 v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
35310 return [v.x / v.w, v.y / v.w, v.z / v.w];
35313 * Transform SfM coordinates to bearing vector (3D cartesian
35314 * coordinates on the unit sphere).
35316 * @param {Array<number>} sfm - 2D SfM coordinates.
35317 * @returns {Array<number>} Bearing vector (3D cartesian coordinates
35318 * on the unit sphere).
35320 Transform.prototype._sfmToBearing = function (sfm) {
35321 if (this._fullPano()) {
35322 var lon = sfm[0] * 2 * Math.PI;
35323 var lat = -sfm[1] * 2 * Math.PI;
35324 var x = Math.cos(lat) * Math.sin(lon);
35325 var y = -Math.sin(lat);
35326 var z = Math.cos(lat) * Math.cos(lon);
35329 else if (this._gpano) {
35330 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
35331 var fullPanoPixel = [
35332 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
35333 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
35335 var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
35336 var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
35337 var x = Math.cos(lat) * Math.sin(lon);
35338 var y = -Math.sin(lat);
35339 var z = Math.cos(lat) * Math.cos(lon);
35343 var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
35345 return [v.x, v.y, v.z];
35349 * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
35352 * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
35354 * @returns {Array<number>} 2D SfM coordinates.
35356 Transform.prototype._bearingToSfm = function (bearing) {
35357 if (this._fullPano()) {
35358 var x = bearing[0];
35359 var y = bearing[1];
35360 var z = bearing[2];
35361 var lon = Math.atan2(x, z);
35362 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
35363 return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
35365 else if (this._gpano) {
35366 var x = bearing[0];
35367 var y = bearing[1];
35368 var z = bearing[2];
35369 var lon = Math.atan2(x, z);
35370 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
35371 var fullPanoPixel = [
35372 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
35373 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
35375 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
35377 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
35378 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
35382 if (bearing[2] > 0) {
35384 bearing[0] * this._focal / bearing[2],
35385 bearing[1] * this._focal / bearing[2],
35390 bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
35391 bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
35397 * Convert basic coordinates to SfM coordinates.
35399 * @param {Array<number>} basic - 2D basic coordinates.
35400 * @returns {Array<number>} 2D SfM coordinates.
35402 Transform.prototype._basicToSfm = function (basic) {
35405 switch (this._orientation) {
35407 rotatedX = basic[0];
35408 rotatedY = basic[1];
35411 rotatedX = 1 - basic[0];
35412 rotatedY = 1 - basic[1];
35415 rotatedX = basic[1];
35416 rotatedY = 1 - basic[0];
35419 rotatedX = 1 - basic[1];
35420 rotatedY = basic[0];
35423 rotatedX = basic[0];
35424 rotatedY = basic[1];
35427 var w = this._width;
35428 var h = this._height;
35429 var s = Math.max(w, h);
35430 var sfmX = rotatedX * w / s - w / s / 2;
35431 var sfmY = rotatedY * h / s - h / s / 2;
35432 return [sfmX, sfmY];
35435 * Convert SfM coordinates to basic coordinates.
35437 * @param {Array<number>} sfm - 2D SfM coordinates.
35438 * @returns {Array<number>} 2D basic coordinates.
35440 Transform.prototype._sfmToBasic = function (sfm) {
35441 var w = this._width;
35442 var h = this._height;
35443 var s = Math.max(w, h);
35444 var rotatedX = (sfm[0] + w / s / 2) / w * s;
35445 var rotatedY = (sfm[1] + h / s / 2) / h * s;
35448 switch (this._orientation) {
35454 basicX = 1 - rotatedX;
35455 basicY = 1 - rotatedY;
35458 basicX = 1 - rotatedY;
35463 basicY = 1 - rotatedX;
35470 return [basicX, basicY];
35473 * Determines if the gpano information indicates a full panorama.
35475 * @returns {boolean} Value determining if the gpano information indicates
35478 Transform.prototype._fullPano = function () {
35479 return this.gpano != null &&
35480 this.gpano.CroppedAreaLeftPixels === 0 &&
35481 this.gpano.CroppedAreaTopPixels === 0 &&
35482 this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
35483 this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
35486 * Checks a value and returns it if it exists and is larger than 0.
35487 * Fallbacks if it is null.
35489 * @param {number} value - Value to check.
35490 * @param {number} fallback - Value to fall back to.
35491 * @returns {number} The value or its fallback value if it is not defined or negative.
35493 Transform.prototype._getValue = function (value, fallback) {
35494 return value != null && value > 0 ? value : fallback;
35497 * Creates the extrinsic camera matrix [ R | t ].
35499 * @param {Array<number>} rotation - Rotation vector in angle axis representation.
35500 * @param {Array<number>} translation - Translation vector.
35501 * @returns {THREE.Matrix4} Extrisic camera matrix.
35503 Transform.prototype._getRt = function (rotation, translation) {
35504 var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
35505 var angle = axis.length();
35509 var rt = new THREE.Matrix4();
35510 rt.makeRotationAxis(axis, angle);
35511 rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
35515 * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
35517 * @param {THREE.Matrix4} rt - Extrisic camera matrix.
35518 * @param {number} scale - Scale factor.
35519 * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
35521 Transform.prototype._getSrt = function (rt, scale) {
35522 var srt = rt.clone();
35523 var elements = srt.elements;
35524 elements[12] = scale * elements[12];
35525 elements[13] = scale * elements[13];
35526 elements[14] = scale * elements[14];
35527 srt.scale(new THREE.Vector3(scale, scale, scale));
35531 * Calculate a transformation matrix from normalized coordinates for
35532 * texture map coordinates.
35534 * @returns {THREE.Matrix4} Normalized coordinates to texture map
35535 * coordinates transformation matrix.
35537 Transform.prototype._normalizedToTextureMatrix = function () {
35538 var size = Math.max(this._width, this._height);
35539 var w = size / this._width;
35540 var h = size / this._height;
35541 switch (this._orientation) {
35543 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
35545 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
35547 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
35549 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
35551 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
35556 exports.Transform = Transform;
35558 },{"three":231}],381:[function(require,module,exports){
35560 /// <reference path="../../typings/index.d.ts" />
35561 Object.defineProperty(exports, "__esModule", { value: true });
35562 var THREE = require("three");
35564 * @class ViewportCoords
35566 * @classdesc Provides methods for calculating 2D coordinate conversions
35567 * as well as 3D projection and unprojection.
35569 * Basic coordinates are 2D coordinates on the [0, 1] interval and
35570 * have the origin point, (0, 0), at the top left corner and the
35571 * maximum value, (1, 1), at the bottom right corner of the original
35574 * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
35575 * have the origin point in the center. The bottom left corner point is
35576 * (-1, -1) and the top right corner point is (1, 1).
35578 * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
35579 * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
35580 * corner and the maximum value is (canvasWidth, canvasHeight) is in the
35581 * bottom right corner.
35583 * 3D coordinates are in the topocentric world reference frame.
35585 var ViewportCoords = /** @class */ (function () {
35586 function ViewportCoords() {
35587 this._unprojectDepth = 200;
35590 * Convert basic coordinates to canvas coordinates.
35592 * @description Transform origin and camera position needs to be the
35593 * equal for reliable return value.
35595 * @param {number} basicX - Basic X coordinate.
35596 * @param {number} basicY - Basic Y coordinate.
35597 * @param {HTMLElement} container - The viewer container.
35598 * @param {Transform} transform - Transform of the node to unproject from.
35599 * @param {THREE.Camera} camera - Camera used in rendering.
35600 * @returns {Array<number>} 2D canvas coordinates.
35602 ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
35603 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
35604 var canvas = this.projectToCanvas(point3d, container, camera);
35608 * Convert basic coordinates to canvas coordinates safely. If 3D point is
35609 * behind camera null will be returned.
35611 * @description Transform origin and camera position needs to be the
35612 * equal for reliable return value.
35614 * @param {number} basicX - Basic X coordinate.
35615 * @param {number} basicY - Basic Y coordinate.
35616 * @param {HTMLElement} container - The viewer container.
35617 * @param {Transform} transform - Transform of the node to unproject from.
35618 * @param {THREE.Camera} camera - Camera used in rendering.
35619 * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
35620 * in front of the camera, otherwise null.
35622 ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
35623 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
35624 var pointCamera = this.worldToCamera(point3d, camera);
35625 if (pointCamera[2] > 0) {
35628 var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1];
35629 var canvas = this.viewportToCanvas(viewportX, viewportY, container);
35633 * Convert basic coordinates to viewport coordinates.
35635 * @description Transform origin and camera position needs to be the
35636 * equal for reliable return value.
35638 * @param {number} basicX - Basic X coordinate.
35639 * @param {number} basicY - Basic Y coordinate.
35640 * @param {Transform} transform - Transform of the node to unproject from.
35641 * @param {THREE.Camera} camera - Camera used in rendering.
35642 * @returns {Array<number>} 2D viewport coordinates.
35644 ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
35645 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
35646 var viewport = this.projectToViewport(point3d, camera);
35650 * Convert camera 3D coordinates to viewport coordinates.
35652 * @param {number} pointCamera - 3D point in camera coordinate system.
35653 * @param {THREE.Camera} camera - Camera used in rendering.
35654 * @returns {Array<number>} 2D viewport coordinates.
35656 ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
35657 var viewport = new THREE.Vector3().fromArray(pointCamera)
35658 .applyMatrix4(camera.projectionMatrix);
35659 return [viewport.x, viewport.y];
35662 * Get canvas pixel position from event.
35664 * @param {Event} event - Event containing clientX and clientY properties.
35665 * @param {HTMLElement} element - HTML element.
35666 * @returns {Array<number>} 2D canvas coordinates.
35668 ViewportCoords.prototype.canvasPosition = function (event, element) {
35669 var clientRect = element.getBoundingClientRect();
35670 var canvasX = event.clientX - clientRect.left - element.clientLeft;
35671 var canvasY = event.clientY - clientRect.top - element.clientTop;
35672 return [canvasX, canvasY];
35675 * Convert canvas coordinates to basic coordinates.
35677 * @description Transform origin and camera position needs to be the
35678 * equal for reliable return value.
35680 * @param {number} canvasX - Canvas X coordinate.
35681 * @param {number} canvasY - Canvas Y coordinate.
35682 * @param {HTMLElement} container - The viewer container.
35683 * @param {Transform} transform - Transform of the node to unproject from.
35684 * @param {THREE.Camera} camera - Camera used in rendering.
35685 * @returns {Array<number>} 2D basic coordinates.
35687 ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
35688 var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
35690 var basic = transform.projectBasic(point3d);
35694 * Convert canvas coordinates to viewport coordinates.
35696 * @param {number} canvasX - Canvas X coordinate.
35697 * @param {number} canvasY - Canvas Y coordinate.
35698 * @param {HTMLElement} container - The viewer container.
35699 * @returns {Array<number>} 2D viewport coordinates.
35701 ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
35702 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
35703 var viewportX = 2 * canvasX / canvasWidth - 1;
35704 var viewportY = 1 - 2 * canvasY / canvasHeight;
35705 return [viewportX, viewportY];
35708 * Determines the width and height of the container in canvas coordinates.
35710 * @param {HTMLElement} container - The viewer container.
35711 * @returns {Array<number>} 2D canvas coordinates.
35713 ViewportCoords.prototype.containerToCanvas = function (container) {
35714 return [container.offsetWidth, container.offsetHeight];
35717 * Determine basic distances from image to canvas corners.
35719 * @description Transform origin and camera position needs to be the
35720 * equal for reliable return value.
35722 * Determines the smallest basic distance for every side of the canvas.
35724 * @param {Transform} transform - Transform of the node to unproject from.
35725 * @param {THREE.Camera} camera - Camera used in rendering.
35726 * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
35728 ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
35729 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
35730 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
35731 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
35732 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
35733 var topBasicDistance = 0;
35734 var rightBasicDistance = 0;
35735 var bottomBasicDistance = 0;
35736 var leftBasicDistance = 0;
35737 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
35738 topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
35742 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
35743 rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
35744 topRightBasic[0] - 1 :
35745 bottomRightBasic[0] - 1;
35747 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
35748 bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
35749 bottomRightBasic[1] - 1 :
35750 bottomLeftBasic[1] - 1;
35752 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
35753 leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
35754 -bottomLeftBasic[0] :
35757 return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
35760 * Determine pixel distances from image to canvas corners.
35762 * @description Transform origin and camera position needs to be the
35763 * equal for reliable return value.
35765 * Determines the smallest pixel distance for every side of the canvas.
35767 * @param {HTMLElement} container - The viewer container.
35768 * @param {Transform} transform - Transform of the node to unproject from.
35769 * @param {THREE.Camera} camera - Camera used in rendering.
35770 * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
35772 ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
35773 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
35774 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
35775 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
35776 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
35777 var topPixelDistance = 0;
35778 var rightPixelDistance = 0;
35779 var bottomPixelDistance = 0;
35780 var leftPixelDistance = 0;
35781 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
35782 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
35783 var basicX = topLeftBasic[1] > topRightBasic[1] ?
35786 var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
35787 topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
35789 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
35790 var basicY = topRightBasic[0] < bottomRightBasic[0] ?
35792 bottomRightBasic[1];
35793 var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
35794 rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
35796 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
35797 var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
35798 bottomRightBasic[0] :
35799 bottomLeftBasic[0];
35800 var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
35801 bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
35803 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
35804 var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
35805 bottomLeftBasic[1] :
35807 var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
35808 leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
35810 return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
35813 * Determine if an event occured inside an element.
35815 * @param {Event} event - Event containing clientX and clientY properties.
35816 * @param {HTMLElement} element - HTML element.
35817 * @returns {boolean} Value indicating if the event occured inside the element or not.
35819 ViewportCoords.prototype.insideElement = function (event, element) {
35820 var clientRect = element.getBoundingClientRect();
35821 var minX = clientRect.left + element.clientLeft;
35822 var maxX = minX + element.clientWidth;
35823 var minY = clientRect.top + element.clientTop;
35824 var maxY = minY + element.clientHeight;
35825 return event.clientX > minX &&
35826 event.clientX < maxX &&
35827 event.clientY > minY &&
35828 event.clientY < maxY;
35831 * Project 3D world coordinates to canvas coordinates.
35833 * @param {Array<number>} point3D - 3D world coordinates.
35834 * @param {HTMLElement} container - The viewer container.
35835 * @param {THREE.Camera} camera - Camera used in rendering.
35836 * @returns {Array<number>} 2D canvas coordinates.
35838 ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
35839 var viewport = this.projectToViewport(point3d, camera);
35840 var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
35844 * Project 3D world coordinates to viewport coordinates.
35846 * @param {Array<number>} point3D - 3D world coordinates.
35847 * @param {THREE.Camera} camera - Camera used in rendering.
35848 * @returns {Array<number>} 2D viewport coordinates.
35850 ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
35851 var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
35853 return [viewport.x, viewport.y];
35856 * Uproject canvas coordinates to 3D world coordinates.
35858 * @param {number} canvasX - Canvas X coordinate.
35859 * @param {number} canvasY - Canvas Y coordinate.
35860 * @param {HTMLElement} container - The viewer container.
35861 * @param {THREE.Camera} camera - Camera used in rendering.
35862 * @returns {Array<number>} 3D world coordinates.
35864 ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
35865 var viewport = this.canvasToViewport(canvasX, canvasY, container);
35866 var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
35870 * Unproject viewport coordinates to 3D world coordinates.
35872 * @param {number} viewportX - Viewport X coordinate.
35873 * @param {number} viewportY - Viewport Y coordinate.
35874 * @param {THREE.Camera} camera - Camera used in rendering.
35875 * @returns {Array<number>} 3D world coordinates.
35877 ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
35878 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
35879 .unproject(camera);
35883 * Convert viewport coordinates to basic coordinates.
35885 * @description Transform origin and camera position needs to be the
35886 * equal for reliable return value.
35888 * @param {number} viewportX - Viewport X coordinate.
35889 * @param {number} viewportY - Viewport Y coordinate.
35890 * @param {Transform} transform - Transform of the node to unproject from.
35891 * @param {THREE.Camera} camera - Camera used in rendering.
35892 * @returns {Array<number>} 2D basic coordinates.
35894 ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
35895 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
35898 var basic = transform.projectBasic(point3d);
35902 * Convert viewport coordinates to canvas coordinates.
35904 * @param {number} viewportX - Viewport X coordinate.
35905 * @param {number} viewportY - Viewport Y coordinate.
35906 * @param {HTMLElement} container - The viewer container.
35907 * @returns {Array<number>} 2D canvas coordinates.
35909 ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
35910 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
35911 var canvasX = canvasWidth * (viewportX + 1) / 2;
35912 var canvasY = -canvasHeight * (viewportY - 1) / 2;
35913 return [canvasX, canvasY];
35916 * Convert 3D world coordinates to 3D camera coordinates.
35918 * @param {number} point3D - 3D point in world coordinate system.
35919 * @param {THREE.Camera} camera - Camera used in rendering.
35920 * @returns {Array<number>} 3D camera coordinates.
35922 ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
35923 var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
35924 .applyMatrix4(camera.matrixWorldInverse);
35925 return pointCamera.toArray();
35927 return ViewportCoords;
35929 exports.ViewportCoords = ViewportCoords;
35930 exports.default = ViewportCoords;
35932 },{"three":231}],382:[function(require,module,exports){
35934 Object.defineProperty(exports, "__esModule", { value: true });
35938 * @classdesc Represents a class for creating node filters. Implementation and
35939 * definitions based on https://github.com/mapbox/feature-filter.
35941 var FilterCreator = /** @class */ (function () {
35942 function FilterCreator() {
35945 * Create a filter from a filter expression.
35947 * @description The following filters are supported:
35964 * @param {FilterExpression} filter - Comparison, set membership or combinding filter
35966 * @returns {FilterFunction} Function taking a node and returning a boolean that
35967 * indicates whether the node passed the test or not.
35969 FilterCreator.prototype.createFilter = function (filter) {
35970 return new Function("node", "return " + this._compile(filter) + ";");
35972 FilterCreator.prototype._compile = function (filter) {
35973 if (filter == null || filter.length <= 1) {
35976 var operator = filter[0];
35977 var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
35978 operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
35979 operator === ">" ||
35980 operator === ">=" ||
35981 operator === "<" ||
35982 operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
35983 operator === "in" ?
35984 this._compileInOp(filter[1], filter.slice(2)) :
35985 operator === "!in" ?
35986 this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
35987 operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
35989 return "(" + operation + ")";
35991 FilterCreator.prototype._compare = function (a, b) {
35992 return a < b ? -1 : a > b ? 1 : 0;
35994 FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
35995 var left = this._compilePropertyReference(property);
35996 var right = JSON.stringify(value);
35997 return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
35999 FilterCreator.prototype._compileInOp = function (property, values) {
36000 var compare = this._compare;
36001 var left = JSON.stringify(values.sort(compare));
36002 var right = this._compilePropertyReference(property);
36003 return left + ".indexOf(" + right + ")!==-1";
36005 FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
36006 var compile = this._compile.bind(this);
36007 return filters.map(compile).join(operator);
36009 FilterCreator.prototype._compileNegation = function (expression) {
36010 return "!(" + expression + ")";
36012 FilterCreator.prototype._compilePropertyReference = function (property) {
36013 return "node[" + JSON.stringify(property) + "]";
36015 return FilterCreator;
36017 exports.FilterCreator = FilterCreator;
36018 exports.default = FilterCreator;
36020 },{}],383:[function(require,module,exports){
36022 /// <reference path="../../typings/index.d.ts" />
36023 Object.defineProperty(exports, "__esModule", { value: true });
36024 var rbush = require("rbush");
36025 var Observable_1 = require("rxjs/Observable");
36026 var Subject_1 = require("rxjs/Subject");
36027 require("rxjs/add/observable/from");
36028 require("rxjs/add/operator/catch");
36029 require("rxjs/add/operator/do");
36030 require("rxjs/add/operator/finally");
36031 require("rxjs/add/operator/map");
36032 require("rxjs/add/operator/publish");
36033 var Edge_1 = require("../Edge");
36034 var Error_1 = require("../Error");
36035 var Graph_1 = require("../Graph");
36039 * @classdesc Represents a graph of nodes with edges.
36041 var Graph = /** @class */ (function () {
36043 * Create a new graph instance.
36045 * @param {APIv3} [apiV3] - API instance for retrieving data.
36046 * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
36047 * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
36048 * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
36049 * @param {FilterCreator} [filterCreator] - Instance for filter creation.
36050 * @param {IGraphConfiguration} [configuration] - Configuration struct.
36052 function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
36053 this._apiV3 = apiV3;
36054 this._cachedNodes = {};
36055 this._cachedNodeTiles = {};
36056 this._cachedSequenceNodes = {};
36057 this._cachedSpatialEdges = {};
36058 this._cachedTiles = {};
36059 this._cachingFill$ = {};
36060 this._cachingFull$ = {};
36061 this._cachingSequenceNodes$ = {};
36062 this._cachingSequences$ = {};
36063 this._cachingSpatialArea$ = {};
36064 this._cachingTiles$ = {};
36065 this._changed$ = new Subject_1.Subject();
36066 this._defaultAlt = 2;
36067 this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
36068 this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
36069 this._filter = this._filterCreator.createFilter(undefined);
36070 this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
36071 this._configuration = configuration != null ?
36075 maxUnusedNodes: 100,
36076 maxUnusedPreStoredNodes: 30,
36077 maxUnusedTiles: 20,
36080 this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
36081 this._nodeIndexTiles = {};
36082 this._nodeToTile = {};
36083 this._preStored = {};
36084 this._requiredNodeTiles = {};
36085 this._requiredSpatialArea = {};
36086 this._sequences = {};
36087 this._tilePrecision = 7;
36088 this._tileThreshold = 20;
36090 Object.defineProperty(Graph.prototype, "changed$", {
36094 * @returns {Observable<Graph>} Observable emitting
36095 * the graph every time it has changed.
36098 return this._changed$;
36104 * Retrieve and cache node fill properties.
36106 * @param {string} key - Key of node to fill.
36107 * @returns {Observable<Graph>} Observable emitting the graph
36108 * when the node has been updated.
36109 * @throws {GraphMapillaryError} When the operation is not valid on the
36112 Graph.prototype.cacheFill$ = function (key) {
36114 if (key in this._cachingFull$) {
36115 throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
36117 if (!this.hasNode(key)) {
36118 throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
36120 if (key in this._cachingFill$) {
36121 return this._cachingFill$[key];
36123 var node = this.getNode(key);
36125 throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
36127 this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
36128 .do(function (imageByKeyFill) {
36130 _this._makeFull(node, imageByKeyFill[key]);
36132 delete _this._cachingFill$[key];
36134 .map(function (imageByKeyFill) {
36137 .finally(function () {
36138 if (key in _this._cachingFill$) {
36139 delete _this._cachingFill$[key];
36141 _this._changed$.next(_this);
36145 return this._cachingFill$[key];
36148 * Retrieve and cache full node properties.
36150 * @param {string} key - Key of node to fill.
36151 * @returns {Observable<Graph>} Observable emitting the graph
36152 * when the node has been updated.
36153 * @throws {GraphMapillaryError} When the operation is not valid on the
36156 Graph.prototype.cacheFull$ = function (key) {
36158 if (key in this._cachingFull$) {
36159 return this._cachingFull$[key];
36161 if (this.hasNode(key)) {
36162 throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
36164 this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
36165 .do(function (imageByKeyFull) {
36166 var fn = imageByKeyFull[key];
36167 if (_this.hasNode(key)) {
36168 var node = _this.getNode(key);
36170 _this._makeFull(node, fn);
36174 if (fn.sequence == null || fn.sequence.key == null) {
36175 throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
36177 var node = new Graph_1.Node(fn);
36178 _this._makeFull(node, fn);
36179 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
36180 _this._preStore(h, node);
36181 _this._setNode(node);
36182 delete _this._cachingFull$[key];
36185 .map(function (imageByKeyFull) {
36188 .finally(function () {
36189 if (key in _this._cachingFull$) {
36190 delete _this._cachingFull$[key];
36192 _this._changed$.next(_this);
36196 return this._cachingFull$[key];
36199 * Retrieve and cache a node sequence.
36201 * @param {string} key - Key of node for which to retrieve sequence.
36202 * @returns {Observable<Graph>} Observable emitting the graph
36203 * when the sequence has been retrieved.
36204 * @throws {GraphMapillaryError} When the operation is not valid on the
36207 Graph.prototype.cacheNodeSequence$ = function (key) {
36208 if (!this.hasNode(key)) {
36209 throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
36211 var node = this.getNode(key);
36212 if (node.sequenceKey in this._sequences) {
36213 throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
36215 return this._cacheSequence$(node.sequenceKey);
36218 * Retrieve and cache a sequence.
36220 * @param {string} sequenceKey - Key of sequence to cache.
36221 * @returns {Observable<Graph>} Observable emitting the graph
36222 * when the sequence has been retrieved.
36223 * @throws {GraphMapillaryError} When the operation is not valid on the
36226 Graph.prototype.cacheSequence$ = function (sequenceKey) {
36227 if (sequenceKey in this._sequences) {
36228 throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
36230 return this._cacheSequence$(sequenceKey);
36233 * Cache sequence edges for a node.
36235 * @param {string} key - Key of node.
36236 * @throws {GraphMapillaryError} When the operation is not valid on the
36239 Graph.prototype.cacheSequenceEdges = function (key) {
36240 var node = this.getNode(key);
36241 if (!(node.sequenceKey in this._sequences)) {
36242 throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
36244 var sequence = this._sequences[node.sequenceKey].sequence;
36245 var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
36246 node.cacheSequenceEdges(edges);
36249 * Retrieve and cache full nodes for all keys in a sequence.
36251 * @param {string} sequenceKey - Key of sequence.
36252 * @param {string} referenceNodeKey - Key of node to use as reference
36253 * for optimized caching.
36254 * @returns {Observable<Graph>} Observable emitting the graph
36255 * when the nodes of the sequence has been cached.
36257 Graph.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
36259 if (!this.hasSequence(sequenceKey)) {
36260 throw new Error_1.GraphMapillaryError("Cannot cache sequence nodes of sequence that does not exist in graph (" + sequenceKey + ").");
36262 if (this.hasSequenceNodes(sequenceKey)) {
36263 throw new Error_1.GraphMapillaryError("Sequence nodes already cached (" + sequenceKey + ").");
36265 var sequence = this.getSequence(sequenceKey);
36266 if (sequence.key in this._cachingSequenceNodes$) {
36267 return this._cachingSequenceNodes$[sequence.key];
36270 var keys = sequence.keys.slice();
36271 if (!!referenceNodeKey) {
36272 var referenceIndex = keys.indexOf(referenceNodeKey);
36273 if (referenceIndex !== -1) {
36274 for (var _i = 0, _a = [20, 40]; _i < _a.length; _i++) {
36275 var referenceBatchSize = _a[_i];
36276 if (referenceIndex < keys.length - 1) {
36277 batches.push(keys.splice(referenceIndex, referenceBatchSize));
36279 if (referenceIndex > 0) {
36280 var shift = referenceIndex === keys.length - 1 ? 1 : 0;
36281 var batch = keys.splice(Math.max(0, referenceIndex + shift - referenceBatchSize), referenceBatchSize);
36282 batches.push(batch);
36283 referenceIndex -= batch.length;
36288 var batchSize = 200;
36289 while (keys.length > 0) {
36290 batches.push(keys.splice(0, batchSize));
36292 var batchesToCache = batches.length;
36293 var sequenceNodes$ = Observable_1.Observable
36295 .mergeMap(function (batch) {
36296 return _this._apiV3.imageByKeyFull$(batch)
36297 .do(function (imageByKeyFull) {
36298 for (var fullKey in imageByKeyFull) {
36299 if (!imageByKeyFull.hasOwnProperty(fullKey)) {
36302 var fn = imageByKeyFull[fullKey];
36303 if (_this.hasNode(fullKey)) {
36304 var node = _this.getNode(fn.key);
36306 _this._makeFull(node, fn);
36310 if (fn.sequence == null || fn.sequence.key == null) {
36311 console.warn("Sequence missing, discarding (" + fn.key + ")");
36313 var node = new Graph_1.Node(fn);
36314 _this._makeFull(node, fn);
36315 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
36316 _this._preStore(h, node);
36317 _this._setNode(node);
36322 .map(function (imageByKeyFull) {
36327 .finally(function () {
36328 delete _this._cachingSequenceNodes$[sequence.key];
36329 if (batchesToCache === 0) {
36330 _this._cachedSequenceNodes[sequence.key] = true;
36335 this._cachingSequenceNodes$[sequence.key] = sequenceNodes$;
36336 return sequenceNodes$;
36339 * Retrieve and cache full nodes for a node spatial area.
36341 * @param {string} key - Key of node for which to retrieve sequence.
36342 * @returns {Observable<Graph>} Observable emitting the graph
36343 * when the nodes in the spatial area has been made full.
36344 * @throws {GraphMapillaryError} When the operation is not valid on the
36347 Graph.prototype.cacheSpatialArea$ = function (key) {
36349 if (!this.hasNode(key)) {
36350 throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
36352 if (key in this._cachedSpatialEdges) {
36353 throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
36355 if (!(key in this._requiredSpatialArea)) {
36356 throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
36358 var spatialArea = this._requiredSpatialArea[key];
36359 if (Object.keys(spatialArea.cacheNodes).length === 0) {
36360 throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
36362 if (key in this._cachingSpatialArea$) {
36363 return this._cachingSpatialArea$[key];
36366 while (spatialArea.cacheKeys.length > 0) {
36367 batches.push(spatialArea.cacheKeys.splice(0, 200));
36369 var batchesToCache = batches.length;
36370 var spatialNodes$ = [];
36371 var _loop_1 = function (batch) {
36372 var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
36373 .do(function (imageByKeyFill) {
36374 for (var fillKey in imageByKeyFill) {
36375 if (!imageByKeyFill.hasOwnProperty(fillKey)) {
36378 var spatialNode = spatialArea.cacheNodes[fillKey];
36379 if (spatialNode.full) {
36380 delete spatialArea.cacheNodes[fillKey];
36383 var fillNode = imageByKeyFill[fillKey];
36384 _this._makeFull(spatialNode, fillNode);
36385 delete spatialArea.cacheNodes[fillKey];
36387 if (--batchesToCache === 0) {
36388 delete _this._cachingSpatialArea$[key];
36391 .map(function (imageByKeyFill) {
36394 .catch(function (error) {
36395 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
36396 var batchKey = batch_1[_i];
36397 if (batchKey in spatialArea.all) {
36398 delete spatialArea.all[batchKey];
36400 if (batchKey in spatialArea.cacheNodes) {
36401 delete spatialArea.cacheNodes[batchKey];
36404 if (--batchesToCache === 0) {
36405 delete _this._cachingSpatialArea$[key];
36409 .finally(function () {
36410 if (Object.keys(spatialArea.cacheNodes).length === 0) {
36411 _this._changed$.next(_this);
36416 spatialNodes$.push(spatialNodeBatch$);
36419 for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
36420 var batch = batches_1[_i];
36423 this._cachingSpatialArea$[key] = spatialNodes$;
36424 return spatialNodes$;
36427 * Cache spatial edges for a node.
36429 * @param {string} key - Key of node.
36430 * @throws {GraphMapillaryError} When the operation is not valid on the
36433 Graph.prototype.cacheSpatialEdges = function (key) {
36434 if (key in this._cachedSpatialEdges) {
36435 throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
36437 var node = this.getNode(key);
36438 var sequence = this._sequences[node.sequenceKey].sequence;
36439 var fallbackKeys = [];
36440 var prevKey = sequence.findPrevKey(node.key);
36441 if (prevKey != null) {
36442 fallbackKeys.push(prevKey);
36444 var nextKey = sequence.findNextKey(node.key);
36445 if (nextKey != null) {
36446 fallbackKeys.push(nextKey);
36448 var allSpatialNodes = this._requiredSpatialArea[key].all;
36449 var potentialNodes = [];
36450 var filter = this._filter;
36451 for (var spatialNodeKey in allSpatialNodes) {
36452 if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
36455 var spatialNode = allSpatialNodes[spatialNodeKey];
36456 if (filter(spatialNode)) {
36457 potentialNodes.push(spatialNode);
36460 var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
36461 var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
36462 edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
36463 edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
36464 edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
36465 edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
36466 node.cacheSpatialEdges(edges);
36467 this._cachedSpatialEdges[key] = node;
36468 delete this._requiredSpatialArea[key];
36469 delete this._cachedNodeTiles[key];
36472 * Retrieve and cache geohash tiles for a node.
36474 * @param {string} key - Key of node for which to retrieve tiles.
36475 * @returns {Observable<Graph>} Observable emitting the graph
36476 * when the tiles required for the node has been cached.
36477 * @throws {GraphMapillaryError} When the operation is not valid on the
36480 Graph.prototype.cacheTiles$ = function (key) {
36482 if (key in this._cachedNodeTiles) {
36483 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
36485 if (key in this._cachedSpatialEdges) {
36486 throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
36488 if (!(key in this._requiredNodeTiles)) {
36489 throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
36491 var nodeTiles = this._requiredNodeTiles[key];
36492 if (nodeTiles.cache.length === 0 &&
36493 nodeTiles.caching.length === 0) {
36494 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
36496 if (!this.hasNode(key)) {
36497 throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
36499 var hs = nodeTiles.cache.slice();
36500 nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
36501 nodeTiles.cache = [];
36502 var cacheTiles$ = [];
36503 var _loop_2 = function (h) {
36504 var cacheTile$ = null;
36505 if (h in this_2._cachingTiles$) {
36506 cacheTile$ = this_2._cachingTiles$[h];
36509 cacheTile$ = this_2._apiV3.imagesByH$([h])
36510 .do(function (imagesByH) {
36511 var coreNodes = imagesByH[h];
36512 if (h in _this._cachedTiles) {
36515 _this._nodeIndexTiles[h] = [];
36516 _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
36517 var hCache = _this._cachedTiles[h].nodes;
36518 var preStored = _this._removeFromPreStore(h);
36519 for (var index in coreNodes) {
36520 if (!coreNodes.hasOwnProperty(index)) {
36523 var coreNode = coreNodes[index];
36524 if (coreNode == null) {
36527 if (coreNode.sequence == null ||
36528 coreNode.sequence.key == null) {
36529 console.warn("Sequence missing, discarding (" + coreNode.key + ")");
36532 if (preStored != null && coreNode.key in preStored) {
36533 var preStoredNode = preStored[coreNode.key];
36534 delete preStored[coreNode.key];
36535 hCache.push(preStoredNode);
36536 var preStoredNodeIndexItem = {
36537 lat: preStoredNode.latLon.lat,
36538 lon: preStoredNode.latLon.lon,
36539 node: preStoredNode,
36541 _this._nodeIndex.insert(preStoredNodeIndexItem);
36542 _this._nodeIndexTiles[h].push(preStoredNodeIndexItem);
36543 _this._nodeToTile[preStoredNode.key] = h;
36546 var node = new Graph_1.Node(coreNode);
36548 var nodeIndexItem = {
36549 lat: node.latLon.lat,
36550 lon: node.latLon.lon,
36553 _this._nodeIndex.insert(nodeIndexItem);
36554 _this._nodeIndexTiles[h].push(nodeIndexItem);
36555 _this._nodeToTile[node.key] = h;
36556 _this._setNode(node);
36558 delete _this._cachingTiles$[h];
36560 .map(function (imagesByH) {
36563 .catch(function (error) {
36564 delete _this._cachingTiles$[h];
36569 this_2._cachingTiles$[h] = cacheTile$;
36571 cacheTiles$.push(cacheTile$
36572 .do(function (graph) {
36573 var index = nodeTiles.caching.indexOf(h);
36575 nodeTiles.caching.splice(index, 1);
36577 if (nodeTiles.caching.length === 0 &&
36578 nodeTiles.cache.length === 0) {
36579 delete _this._requiredNodeTiles[key];
36580 _this._cachedNodeTiles[key] = true;
36583 .catch(function (error) {
36584 var index = nodeTiles.caching.indexOf(h);
36586 nodeTiles.caching.splice(index, 1);
36588 if (nodeTiles.caching.length === 0 &&
36589 nodeTiles.cache.length === 0) {
36590 delete _this._requiredNodeTiles[key];
36591 _this._cachedNodeTiles[key] = true;
36595 .finally(function () {
36596 _this._changed$.next(_this);
36602 for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
36606 return cacheTiles$;
36609 * Initialize the cache for a node.
36611 * @param {string} key - Key of node.
36612 * @throws {GraphMapillaryError} When the operation is not valid on the
36615 Graph.prototype.initializeCache = function (key) {
36616 if (key in this._cachedNodes) {
36617 throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
36619 var node = this.getNode(key);
36620 node.initializeCache(new Graph_1.NodeCache());
36621 var accessed = new Date().getTime();
36622 this._cachedNodes[key] = { accessed: accessed, node: node };
36623 this._updateCachedTileAccess(key, accessed);
36626 * Get a value indicating if the graph is fill caching a node.
36628 * @param {string} key - Key of node.
36629 * @returns {boolean} Value indicating if the node is being fill cached.
36631 Graph.prototype.isCachingFill = function (key) {
36632 return key in this._cachingFill$;
36635 * Get a value indicating if the graph is fully caching a node.
36637 * @param {string} key - Key of node.
36638 * @returns {boolean} Value indicating if the node is being fully cached.
36640 Graph.prototype.isCachingFull = function (key) {
36641 return key in this._cachingFull$;
36644 * Get a value indicating if the graph is caching a sequence of a node.
36646 * @param {string} key - Key of node.
36647 * @returns {boolean} Value indicating if the sequence of a node is
36650 Graph.prototype.isCachingNodeSequence = function (key) {
36651 var node = this.getNode(key);
36652 return node.sequenceKey in this._cachingSequences$;
36655 * Get a value indicating if the graph is caching a sequence.
36657 * @param {string} sequenceKey - Key of sequence.
36658 * @returns {boolean} Value indicating if the sequence is
36661 Graph.prototype.isCachingSequence = function (sequenceKey) {
36662 return sequenceKey in this._cachingSequences$;
36665 * Get a value indicating if the graph is caching sequence nodes.
36667 * @param {string} sequenceKey - Key of sequence.
36668 * @returns {boolean} Value indicating if the sequence nodes are
36671 Graph.prototype.isCachingSequenceNodes = function (sequenceKey) {
36672 return sequenceKey in this._cachingSequenceNodes$;
36675 * Get a value indicating if the graph is caching the tiles
36676 * required for calculating spatial edges of a node.
36678 * @param {string} key - Key of node.
36679 * @returns {boolean} Value indicating if the tiles of
36680 * a node are being cached.
36682 Graph.prototype.isCachingTiles = function (key) {
36683 return key in this._requiredNodeTiles &&
36684 this._requiredNodeTiles[key].cache.length === 0 &&
36685 this._requiredNodeTiles[key].caching.length > 0;
36688 * Get a value indicating if the cache has been initialized
36691 * @param {string} key - Key of node.
36692 * @returns {boolean} Value indicating if the cache has been
36693 * initialized for a node.
36695 Graph.prototype.hasInitializedCache = function (key) {
36696 return key in this._cachedNodes;
36699 * Get a value indicating if a node exist in the graph.
36701 * @param {string} key - Key of node.
36702 * @returns {boolean} Value indicating if a node exist in the graph.
36704 Graph.prototype.hasNode = function (key) {
36705 var accessed = new Date().getTime();
36706 this._updateCachedNodeAccess(key, accessed);
36707 this._updateCachedTileAccess(key, accessed);
36708 return key in this._nodes;
36711 * Get a value indicating if a node sequence exist in the graph.
36713 * @param {string} key - Key of node.
36714 * @returns {boolean} Value indicating if a node sequence exist
36717 Graph.prototype.hasNodeSequence = function (key) {
36718 var node = this.getNode(key);
36719 var sequenceKey = node.sequenceKey;
36720 var hasNodeSequence = sequenceKey in this._sequences;
36721 if (hasNodeSequence) {
36722 this._sequences[sequenceKey].accessed = new Date().getTime();
36724 return hasNodeSequence;
36727 * Get a value indicating if a sequence exist in the graph.
36729 * @param {string} sequenceKey - Key of sequence.
36730 * @returns {boolean} Value indicating if a sequence exist
36733 Graph.prototype.hasSequence = function (sequenceKey) {
36734 var hasSequence = sequenceKey in this._sequences;
36736 this._sequences[sequenceKey].accessed = new Date().getTime();
36738 return hasSequence;
36741 * Get a value indicating if sequence nodes has been cached in the graph.
36743 * @param {string} sequenceKey - Key of sequence.
36744 * @returns {boolean} Value indicating if a sequence nodes has been
36745 * cached in the graph.
36747 Graph.prototype.hasSequenceNodes = function (sequenceKey) {
36748 return sequenceKey in this._cachedSequenceNodes;
36751 * Get a value indicating if the graph has fully cached
36752 * all nodes in the spatial area of a node.
36754 * @param {string} key - Key of node.
36755 * @returns {boolean} Value indicating if the spatial area
36756 * of a node has been cached.
36758 Graph.prototype.hasSpatialArea = function (key) {
36759 if (!this.hasNode(key)) {
36760 throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
36762 if (key in this._cachedSpatialEdges) {
36765 if (key in this._requiredSpatialArea) {
36766 return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
36768 var node = this.getNode(key);
36769 var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
36770 var spatialItems = this._nodeIndex.search({
36776 var spatialNodes = {
36781 for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
36782 var spatialItem = spatialItems_1[_i];
36783 spatialNodes.all[spatialItem.node.key] = spatialItem.node;
36784 if (!spatialItem.node.full) {
36785 spatialNodes.cacheKeys.push(spatialItem.node.key);
36786 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
36789 this._requiredSpatialArea[key] = spatialNodes;
36790 return spatialNodes.cacheKeys.length === 0;
36793 * Get a value indicating if the graph has a tiles required
36796 * @param {string} key - Key of node.
36797 * @returns {boolean} Value indicating if the the tiles required
36798 * by a node has been cached.
36800 Graph.prototype.hasTiles = function (key) {
36802 if (key in this._cachedNodeTiles) {
36805 if (key in this._cachedSpatialEdges) {
36808 if (!this.hasNode(key)) {
36809 throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
36811 var nodeTiles = { cache: [], caching: [] };
36812 if (!(key in this._requiredNodeTiles)) {
36813 var node = this.getNode(key);
36814 nodeTiles.cache = this._graphCalculator
36815 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
36816 .filter(function (h) {
36817 return !(h in _this._cachedTiles);
36819 if (nodeTiles.cache.length > 0) {
36820 this._requiredNodeTiles[key] = nodeTiles;
36824 nodeTiles = this._requiredNodeTiles[key];
36826 return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
36831 * @param {string} key - Key of node.
36832 * @returns {Node} Retrieved node.
36834 Graph.prototype.getNode = function (key) {
36835 var accessed = new Date().getTime();
36836 this._updateCachedNodeAccess(key, accessed);
36837 this._updateCachedTileAccess(key, accessed);
36838 return this._nodes[key];
36843 * @param {string} sequenceKey - Key of sequence.
36844 * @returns {Node} Retrieved sequence.
36846 Graph.prototype.getSequence = function (sequenceKey) {
36847 var sequenceAccess = this._sequences[sequenceKey];
36848 sequenceAccess.accessed = new Date().getTime();
36849 return sequenceAccess.sequence;
36852 * Reset all spatial edges of the graph nodes.
36854 Graph.prototype.resetSpatialEdges = function () {
36855 var cachedKeys = Object.keys(this._cachedSpatialEdges);
36856 for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
36857 var cachedKey = cachedKeys_1[_i];
36858 var node = this._cachedSpatialEdges[cachedKey];
36859 node.resetSpatialEdges();
36860 delete this._cachedSpatialEdges[cachedKey];
36864 * Reset the complete graph but keep the nodes corresponding
36865 * to the supplied keys. All other nodes will be disposed.
36867 * @param {Array<string>} keepKeys - Keys for nodes to keep
36868 * in graph after reset.
36870 Graph.prototype.reset = function (keepKeys) {
36872 for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
36873 var key = keepKeys_1[_i];
36874 if (!this.hasNode(key)) {
36875 throw new Error("Node does not exist " + key);
36877 var node = this.getNode(key);
36878 node.resetSequenceEdges();
36879 node.resetSpatialEdges();
36882 for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
36883 var cachedKey = _b[_a];
36884 if (keepKeys.indexOf(cachedKey) !== -1) {
36887 this._cachedNodes[cachedKey].node.dispose();
36888 delete this._cachedNodes[cachedKey];
36890 this._cachedNodeTiles = {};
36891 this._cachedSpatialEdges = {};
36892 this._cachedTiles = {};
36893 this._cachingFill$ = {};
36894 this._cachingFull$ = {};
36895 this._cachingSequences$ = {};
36896 this._cachingSpatialArea$ = {};
36897 this._cachingTiles$ = {};
36899 this._nodeToTile = {};
36900 this._preStored = {};
36901 for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
36902 var node = nodes_1[_c];
36903 this._nodes[node.key] = node;
36904 var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
36905 this._preStore(h, node);
36907 this._requiredNodeTiles = {};
36908 this._requiredSpatialArea = {};
36909 this._sequences = {};
36910 this._nodeIndexTiles = {};
36911 this._nodeIndex.clear();
36914 * Set the spatial node filter.
36916 * @param {FilterExpression} filter - Filter expression to be applied
36917 * when calculating spatial edges.
36919 Graph.prototype.setFilter = function (filter) {
36920 this._filter = this._filterCreator.createFilter(filter);
36923 * Uncache the graph according to the graph configuration.
36925 * @description Uncaches unused tiles, unused nodes and
36926 * sequences according to the numbers specified in the
36927 * graph configuration. Sequences does not have a direct
36928 * reference to either tiles or nodes and may be uncached
36929 * even if they are related to the nodes that should be kept.
36931 * @param {Array<string>} keepKeys - Keys of nodes to keep in
36932 * graph unrelated to last access. Tiles related to those keys
36933 * will also be kept in graph.
36934 * @param {string} keepSequenceKey - Optional key of sequence
36935 * for which the belonging nodes should not be disposed or
36936 * removed from the graph. These nodes may still be uncached if
36937 * not specified in keep keys param.
36939 Graph.prototype.uncache = function (keepKeys, keepSequenceKey) {
36940 var keysInUse = {};
36941 this._addNewKeys(keysInUse, this._cachingFull$);
36942 this._addNewKeys(keysInUse, this._cachingFill$);
36943 this._addNewKeys(keysInUse, this._cachingSpatialArea$);
36944 this._addNewKeys(keysInUse, this._requiredNodeTiles);
36945 this._addNewKeys(keysInUse, this._requiredSpatialArea);
36946 for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
36947 var key = keepKeys_2[_i];
36948 if (key in keysInUse) {
36951 keysInUse[key] = true;
36954 for (var key in keysInUse) {
36955 if (!keysInUse.hasOwnProperty(key)) {
36958 var node = this._nodes[key];
36959 var nodeHs = this._graphCalculator.encodeHs(node.latLon);
36960 for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
36961 var nodeH = nodeHs_1[_a];
36962 if (!(nodeH in keepHs)) {
36963 keepHs[nodeH] = true;
36967 var potentialHs = [];
36968 for (var h in this._cachedTiles) {
36969 if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
36972 potentialHs.push([h, this._cachedTiles[h]]);
36974 var uncacheHs = potentialHs
36975 .sort(function (h1, h2) {
36976 return h2[1].accessed - h1[1].accessed;
36978 .slice(this._configuration.maxUnusedTiles)
36979 .map(function (h) {
36982 for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
36983 var uncacheH = uncacheHs_1[_b];
36984 this._uncacheTile(uncacheH, keepSequenceKey);
36986 var potentialPreStored = [];
36987 var nonCachedPreStored = [];
36988 for (var h in this._preStored) {
36989 if (!this._preStored.hasOwnProperty(h) || h in this._cachingTiles$) {
36992 var prestoredNodes = this._preStored[h];
36993 for (var key in prestoredNodes) {
36994 if (!prestoredNodes.hasOwnProperty(key) || key in keysInUse) {
36997 if (prestoredNodes[key].sequenceKey === keepSequenceKey) {
37000 if (key in this._cachedNodes) {
37001 potentialPreStored.push([this._cachedNodes[key], h]);
37004 nonCachedPreStored.push([key, h]);
37008 var uncachePreStored = potentialPreStored
37009 .sort(function (_a, _b) {
37010 var na1 = _a[0], h1 = _a[1];
37011 var na2 = _b[0], h2 = _b[1];
37012 return na2.accessed - na1.accessed;
37014 .slice(this._configuration.maxUnusedPreStoredNodes)
37015 .map(function (_a) {
37016 var na = _a[0], h = _a[1];
37017 return [na.node.key, h];
37019 this._uncachePreStored(nonCachedPreStored);
37020 this._uncachePreStored(uncachePreStored);
37021 var potentialNodes = [];
37022 for (var key in this._cachedNodes) {
37023 if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
37026 potentialNodes.push(this._cachedNodes[key]);
37028 var uncacheNodes = potentialNodes
37029 .sort(function (n1, n2) {
37030 return n2.accessed - n1.accessed;
37032 .slice(this._configuration.maxUnusedNodes);
37033 for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
37034 var nodeAccess = uncacheNodes_1[_c];
37035 nodeAccess.node.uncache();
37036 var key = nodeAccess.node.key;
37037 delete this._cachedNodes[key];
37038 if (key in this._cachedNodeTiles) {
37039 delete this._cachedNodeTiles[key];
37041 if (key in this._cachedSpatialEdges) {
37042 delete this._cachedSpatialEdges[key];
37045 var potentialSequences = [];
37046 for (var sequenceKey in this._sequences) {
37047 if (!this._sequences.hasOwnProperty(sequenceKey) ||
37048 sequenceKey in this._cachingSequences$ ||
37049 sequenceKey === keepSequenceKey) {
37052 potentialSequences.push(this._sequences[sequenceKey]);
37054 var uncacheSequences = potentialSequences
37055 .sort(function (s1, s2) {
37056 return s2.accessed - s1.accessed;
37058 .slice(this._configuration.maxSequences);
37059 for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
37060 var sequenceAccess = uncacheSequences_1[_d];
37061 var sequenceKey = sequenceAccess.sequence.key;
37062 delete this._sequences[sequenceKey];
37063 if (sequenceKey in this._cachedSequenceNodes) {
37064 delete this._cachedSequenceNodes[sequenceKey];
37066 sequenceAccess.sequence.dispose();
37069 Graph.prototype._addNewKeys = function (keys, dict) {
37070 for (var key in dict) {
37071 if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
37074 if (!(key in keys)) {
37079 Graph.prototype._cacheSequence$ = function (sequenceKey) {
37081 if (sequenceKey in this._cachingSequences$) {
37082 return this._cachingSequences$[sequenceKey];
37084 this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
37085 .do(function (sequenceByKey) {
37086 if (!(sequenceKey in _this._sequences)) {
37087 _this._sequences[sequenceKey] = {
37088 accessed: new Date().getTime(),
37089 sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
37092 delete _this._cachingSequences$[sequenceKey];
37094 .map(function (sequenceByKey) {
37097 .finally(function () {
37098 if (sequenceKey in _this._cachingSequences$) {
37099 delete _this._cachingSequences$[sequenceKey];
37101 _this._changed$.next(_this);
37105 return this._cachingSequences$[sequenceKey];
37107 Graph.prototype._makeFull = function (node, fillNode) {
37108 if (fillNode.calt == null) {
37109 fillNode.calt = this._defaultAlt;
37111 if (fillNode.c_rotation == null) {
37112 fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
37114 node.makeFull(fillNode);
37116 Graph.prototype._preStore = function (h, node) {
37117 if (!(h in this._preStored)) {
37118 this._preStored[h] = {};
37120 this._preStored[h][node.key] = node;
37122 Graph.prototype._removeFromPreStore = function (h) {
37123 var preStored = null;
37124 if (h in this._preStored) {
37125 preStored = this._preStored[h];
37126 delete this._preStored[h];
37130 Graph.prototype._setNode = function (node) {
37131 var key = node.key;
37132 if (this.hasNode(key)) {
37133 throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
37135 this._nodes[key] = node;
37137 Graph.prototype._uncacheTile = function (h, keepSequenceKey) {
37138 for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
37140 var key = node.key;
37141 delete this._nodeToTile[key];
37142 if (key in this._cachedNodes) {
37143 delete this._cachedNodes[key];
37145 if (key in this._cachedNodeTiles) {
37146 delete this._cachedNodeTiles[key];
37148 if (key in this._cachedSpatialEdges) {
37149 delete this._cachedSpatialEdges[key];
37151 if (node.sequenceKey === keepSequenceKey) {
37152 this._preStore(h, node);
37156 delete this._nodes[key];
37157 if (node.sequenceKey in this._cachedSequenceNodes) {
37158 delete this._cachedSequenceNodes[node.sequenceKey];
37163 for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
37164 var nodeIndexItem = _c[_b];
37165 this._nodeIndex.remove(nodeIndexItem);
37167 delete this._nodeIndexTiles[h];
37168 delete this._cachedTiles[h];
37170 Graph.prototype._uncachePreStored = function (preStored) {
37172 for (var _i = 0, preStored_1 = preStored; _i < preStored_1.length; _i++) {
37173 var _a = preStored_1[_i], key = _a[0], h = _a[1];
37174 if (key in this._nodes) {
37175 delete this._nodes[key];
37177 if (key in this._cachedNodes) {
37178 delete this._cachedNodes[key];
37180 var node = this._preStored[h][key];
37181 if (node.sequenceKey in this._cachedSequenceNodes) {
37182 delete this._cachedSequenceNodes[node.sequenceKey];
37184 delete this._preStored[h][key];
37188 for (var h in hs) {
37189 if (!hs.hasOwnProperty(h)) {
37192 if (Object.keys(this._preStored[h]).length === 0) {
37193 delete this._preStored[h];
37197 Graph.prototype._updateCachedTileAccess = function (key, accessed) {
37198 if (key in this._nodeToTile) {
37199 this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
37202 Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
37203 if (key in this._cachedNodes) {
37204 this._cachedNodes[key].accessed = accessed;
37209 exports.Graph = Graph;
37210 exports.default = Graph;
37212 },{"../Edge":282,"../Error":283,"../Graph":285,"rbush":25,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/from":41,"rxjs/add/operator/catch":52,"rxjs/add/operator/do":59,"rxjs/add/operator/finally":62,"rxjs/add/operator/map":65,"rxjs/add/operator/publish":71}],384:[function(require,module,exports){
37214 /// <reference path="../../typings/index.d.ts" />
37215 Object.defineProperty(exports, "__esModule", { value: true });
37216 var geohash = require("latlon-geohash");
37217 var THREE = require("three");
37218 var Geo_1 = require("../Geo");
37219 var GeoHashDirections = /** @class */ (function () {
37220 function GeoHashDirections() {
37222 GeoHashDirections.n = "n";
37223 GeoHashDirections.nw = "nw";
37224 GeoHashDirections.w = "w";
37225 GeoHashDirections.sw = "sw";
37226 GeoHashDirections.s = "s";
37227 GeoHashDirections.se = "se";
37228 GeoHashDirections.e = "e";
37229 GeoHashDirections.ne = "ne";
37230 return GeoHashDirections;
37233 * @class GraphCalculator
37235 * @classdesc Represents a calculator for graph entities.
37237 var GraphCalculator = /** @class */ (function () {
37239 * Create a new graph calculator instance.
37241 * @param {GeoCoords} geoCoords - Geo coords instance.
37243 function GraphCalculator(geoCoords) {
37244 this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
37247 * Encode the geohash tile for geodetic coordinates.
37249 * @param {ILatLon} latlon - Latitude and longitude to encode.
37250 * @param {number} precision - Precision of the encoding.
37252 * @returns {string} The geohash tile for the lat, lon and precision.
37254 GraphCalculator.prototype.encodeH = function (latLon, precision) {
37255 if (precision === void 0) { precision = 7; }
37256 return geohash.encode(latLon.lat, latLon.lon, precision);
37259 * Encode the geohash tiles within a threshold from a position
37260 * using Manhattan distance.
37262 * @param {ILatLon} latlon - Latitude and longitude to encode.
37263 * @param {number} precision - Precision of the encoding.
37264 * @param {number} threshold - Threshold of the encoding in meters.
37266 * @returns {string} The geohash tiles reachable within the threshold.
37268 GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
37269 if (precision === void 0) { precision = 7; }
37270 if (threshold === void 0) { threshold = 20; }
37271 var h = geohash.encode(latLon.lat, latLon.lon, precision);
37272 var bounds = geohash.bounds(h);
37273 var ne = bounds.ne;
37274 var sw = bounds.sw;
37275 var neighbours = geohash.neighbours(h);
37276 var bl = [0, 0, 0];
37277 var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
37278 var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
37279 var left = position[0] - bl[0];
37280 var right = tr[0] - position[0];
37281 var bottom = position[1] - bl[1];
37282 var top = tr[1] - position[1];
37283 var l = left < threshold;
37284 var r = right < threshold;
37285 var b = bottom < threshold;
37286 var t = top < threshold;
37289 hs.push(neighbours[GeoHashDirections.n]);
37292 hs.push(neighbours[GeoHashDirections.nw]);
37295 hs.push(neighbours[GeoHashDirections.w]);
37298 hs.push(neighbours[GeoHashDirections.sw]);
37301 hs.push(neighbours[GeoHashDirections.s]);
37304 hs.push(neighbours[GeoHashDirections.se]);
37307 hs.push(neighbours[GeoHashDirections.e]);
37310 hs.push(neighbours[GeoHashDirections.ne]);
37315 * Get the bounding box corners for a circle with radius of a threshold
37316 * with center in a geodetic position.
37318 * @param {ILatLon} latlon - Latitude and longitude to encode.
37319 * @param {number} threshold - Threshold distance from the position in meters.
37321 * @returns {Array<ILatLon>} The south west and north east corners of the
37324 GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
37325 var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
37326 var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
37328 { lat: bl[0], lon: bl[1] },
37329 { lat: tr[0], lon: tr[1] },
37333 * Convert a compass angle to an angle axis rotation vector.
37335 * @param {number} compassAngle - The compass angle in degrees.
37336 * @param {number} orientation - The orientation of the original image.
37338 * @returns {Array<number>} Angle axis rotation vector.
37340 GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
37344 switch (orientation) {
37363 var rz = new THREE.Matrix4().makeRotationZ(z);
37364 var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
37365 var re = new THREE.Matrix4().makeRotationFromEuler(euler);
37366 var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
37367 return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
37369 return GraphCalculator;
37371 exports.GraphCalculator = GraphCalculator;
37372 exports.default = GraphCalculator;
37374 },{"../Geo":284,"latlon-geohash":21,"three":231}],385:[function(require,module,exports){
37376 Object.defineProperty(exports, "__esModule", { value: true });
37378 * Enumeration for graph modes.
37381 * @description Modes for the retrieval and caching performed
37382 * by the graph service on the graph.
37385 (function (GraphMode) {
37387 * Caching is performed on sequences only and sequence edges are
37388 * calculated. Spatial tiles
37389 * are not retrieved and spatial edges are not calculated when
37390 * caching nodes. Complete sequences are being cached for requested
37391 * nodes within the graph.
37393 GraphMode[GraphMode["Sequence"] = 0] = "Sequence";
37395 * Caching is performed with emphasis on spatial data. Sequence edges
37396 * as well as spatial edges are cached. Sequence data
37397 * is still requested but complete sequences are not being cached
37398 * for requested nodes.
37400 * This is the initial mode of the graph service.
37402 GraphMode[GraphMode["Spatial"] = 1] = "Spatial";
37403 })(GraphMode = exports.GraphMode || (exports.GraphMode = {}));
37404 exports.default = GraphMode;
37406 },{}],386:[function(require,module,exports){
37408 Object.defineProperty(exports, "__esModule", { value: true });
37409 var Observable_1 = require("rxjs/Observable");
37410 var Subject_1 = require("rxjs/Subject");
37411 require("rxjs/add/operator/catch");
37412 require("rxjs/add/operator/concat");
37413 require("rxjs/add/operator/do");
37414 require("rxjs/add/operator/expand");
37415 require("rxjs/add/operator/finally");
37416 require("rxjs/add/operator/first");
37417 require("rxjs/add/operator/last");
37418 require("rxjs/add/operator/map");
37419 require("rxjs/add/operator/mergeMap");
37420 require("rxjs/add/operator/publishReplay");
37421 var Graph_1 = require("../Graph");
37423 * @class GraphService
37425 * @classdesc Represents a service for graph operations.
37427 var GraphService = /** @class */ (function () {
37429 * Create a new graph service instance.
37431 * @param {Graph} graph - Graph instance to be operated on.
37433 function GraphService(graph, imageLoadingService) {
37434 this._graph$ = Observable_1.Observable
37436 .concat(graph.changed$)
37439 this._graph$.subscribe(function () { });
37440 this._graphMode = Graph_1.GraphMode.Spatial;
37441 this._graphModeSubject$ = new Subject_1.Subject();
37442 this._graphMode$ = this._graphModeSubject$
37443 .startWith(this._graphMode)
37446 this._graphMode$.subscribe(function () { });
37447 this._imageLoadingService = imageLoadingService;
37448 this._firstGraphSubjects$ = [];
37449 this._initializeCacheSubscriptions = [];
37450 this._sequenceSubscriptions = [];
37451 this._spatialSubscriptions = [];
37453 Object.defineProperty(GraphService.prototype, "graphMode$", {
37455 * Get graph mode observable.
37457 * @description Emits the current graph mode.
37459 * @returns {Observable<GraphMode>} Observable
37460 * emitting the current graph mode when it changes.
37463 return this._graphMode$;
37469 * Cache a node in the graph and retrieve it.
37471 * @description When called, the full properties of
37472 * the node are retrieved and the node cache is initialized.
37473 * After that the node assets are cached and the node
37474 * is emitted to the observable when.
37475 * In parallel to caching the node assets, the sequence and
37476 * spatial edges of the node are cached. For this, the sequence
37477 * of the node and the required tiles and spatial nodes are
37478 * retrieved. The sequence and spatial edges may be set before
37479 * or after the node is returned.
37481 * @param {string} key - Key of the node to cache.
37482 * @return {Observable<Node>} Observable emitting a single item,
37483 * the node, when it has been retrieved and its assets are cached.
37484 * @throws {Error} Propagates any IO node caching errors to the caller.
37486 GraphService.prototype.cacheNode$ = function (key) {
37488 var firstGraphSubject$ = new Subject_1.Subject();
37489 this._firstGraphSubjects$.push(firstGraphSubject$);
37490 var firstGraph$ = firstGraphSubject$
37493 var node$ = firstGraph$
37494 .map(function (graph) {
37495 return graph.getNode(key);
37497 .mergeMap(function (node) {
37498 return node.assetsCached ?
37499 Observable_1.Observable.of(node) :
37500 node.cacheAssets$();
37504 node$.subscribe(function (node) {
37505 _this._imageLoadingService.loadnode$.next(node);
37506 }, function (error) {
37507 console.error("Failed to cache node (" + key + ")", error);
37509 var initializeCacheSubscription = this._graph$
37511 .mergeMap(function (graph) {
37512 if (graph.isCachingFull(key) || !graph.hasNode(key)) {
37513 return graph.cacheFull$(key);
37515 if (graph.isCachingFill(key) || !graph.getNode(key).full) {
37516 return graph.cacheFill$(key);
37518 return Observable_1.Observable.of(graph);
37520 .do(function (graph) {
37521 if (!graph.hasInitializedCache(key)) {
37522 graph.initializeCache(key);
37525 .finally(function () {
37526 if (initializeCacheSubscription == null) {
37529 _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
37530 _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
37532 .subscribe(function (graph) {
37533 firstGraphSubject$.next(graph);
37534 firstGraphSubject$.complete();
37535 }, function (error) {
37536 firstGraphSubject$.error(error);
37538 if (!initializeCacheSubscription.closed) {
37539 this._initializeCacheSubscriptions.push(initializeCacheSubscription);
37541 var graphSequence$ = firstGraph$
37542 .mergeMap(function (graph) {
37543 if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
37544 return graph.cacheNodeSequence$(key);
37546 return Observable_1.Observable.of(graph);
37550 var sequenceSubscription = graphSequence$
37551 .do(function (graph) {
37552 if (!graph.getNode(key).sequenceEdges.cached) {
37553 graph.cacheSequenceEdges(key);
37556 .finally(function () {
37557 if (sequenceSubscription == null) {
37560 _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
37562 .subscribe(function (graph) { return; }, function (error) {
37563 console.error("Failed to cache sequence edges (" + key + ").", error);
37565 if (!sequenceSubscription.closed) {
37566 this._sequenceSubscriptions.push(sequenceSubscription);
37568 if (this._graphMode === Graph_1.GraphMode.Spatial) {
37569 var spatialSubscription_1 = firstGraph$
37570 .expand(function (graph) {
37571 if (graph.hasTiles(key)) {
37572 return Observable_1.Observable.empty();
37574 return Observable_1.Observable
37575 .from(graph.cacheTiles$(key))
37576 .mergeMap(function (graph$) {
37578 .mergeMap(function (g) {
37579 if (g.isCachingTiles(key)) {
37580 return Observable_1.Observable.empty();
37582 return Observable_1.Observable.of(g);
37584 .catch(function (error, caught$) {
37585 console.error("Failed to cache tile data (" + key + ").", error);
37586 return Observable_1.Observable.empty();
37591 .mergeMap(function (graph) {
37592 if (graph.hasSpatialArea(key)) {
37593 return Observable_1.Observable.of(graph);
37595 return Observable_1.Observable
37596 .from(graph.cacheSpatialArea$(key))
37597 .mergeMap(function (graph$) {
37599 .catch(function (error, caught$) {
37600 console.error("Failed to cache spatial nodes (" + key + ").", error);
37601 return Observable_1.Observable.empty();
37606 .mergeMap(function (graph) {
37607 return graph.hasNodeSequence(key) ?
37608 Observable_1.Observable.of(graph) :
37609 graph.cacheNodeSequence$(key);
37611 .do(function (graph) {
37612 if (!graph.getNode(key).spatialEdges.cached) {
37613 graph.cacheSpatialEdges(key);
37616 .finally(function () {
37617 if (spatialSubscription_1 == null) {
37620 _this._removeFromArray(spatialSubscription_1, _this._spatialSubscriptions);
37622 .subscribe(function (graph) { return; }, function (error) {
37623 console.error("Failed to cache spatial edges (" + key + ").", error);
37625 if (!spatialSubscription_1.closed) {
37626 this._spatialSubscriptions.push(spatialSubscription_1);
37630 .first(function (node) {
37631 return node.assetsCached;
37635 * Cache a sequence in the graph and retrieve it.
37637 * @param {string} sequenceKey - Sequence key.
37638 * @returns {Observable<Sequence>} Observable emitting a single item,
37639 * the sequence, when it has been retrieved and its assets are cached.
37640 * @throws {Error} Propagates any IO node caching errors to the caller.
37642 GraphService.prototype.cacheSequence$ = function (sequenceKey) {
37643 return this._graph$
37645 .mergeMap(function (graph) {
37646 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
37647 return graph.cacheSequence$(sequenceKey);
37649 return Observable_1.Observable.of(graph);
37651 .map(function (graph) {
37652 return graph.getSequence(sequenceKey);
37656 * Cache a sequence and its nodes in the graph and retrieve the sequence.
37658 * @description Caches a sequence and its assets are cached and
37659 * retrieves all nodes belonging to the sequence. The node assets
37660 * or edges will not be cached.
37662 * @param {string} sequenceKey - Sequence key.
37663 * @param {string} referenceNodeKey - Key of node to use as reference
37664 * for optimized caching.
37665 * @returns {Observable<Sequence>} Observable emitting a single item,
37666 * the sequence, when it has been retrieved, its assets are cached and
37667 * all nodes belonging to the sequence has been retrieved.
37668 * @throws {Error} Propagates any IO node caching errors to the caller.
37670 GraphService.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
37671 return this._graph$
37673 .mergeMap(function (graph) {
37674 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
37675 return graph.cacheSequence$(sequenceKey);
37677 return Observable_1.Observable.of(graph);
37679 .mergeMap(function (graph) {
37680 if (graph.isCachingSequenceNodes(sequenceKey) || !graph.hasSequenceNodes(sequenceKey)) {
37681 return graph.cacheSequenceNodes$(sequenceKey, referenceNodeKey);
37683 return Observable_1.Observable.of(graph);
37685 .map(function (graph) {
37686 return graph.getSequence(sequenceKey);
37690 * Set a spatial edge filter on the graph.
37692 * @description Resets the spatial edges of all cached nodes.
37694 * @param {FilterExpression} filter - Filter expression to be applied.
37695 * @return {Observable<Graph>} Observable emitting a single item,
37696 * the graph, when the spatial edges have been reset.
37698 GraphService.prototype.setFilter$ = function (filter) {
37699 this._resetSubscriptions(this._spatialSubscriptions);
37700 return this._graph$
37702 .do(function (graph) {
37703 graph.resetSpatialEdges();
37704 graph.setFilter(filter);
37706 .map(function (graph) {
37711 * Set the graph mode.
37713 * @description If graph mode is set to spatial, caching
37714 * is performed with emphasis on spatial edges. If graph
37715 * mode is set to sequence no tile data is requested and
37716 * no spatial edges are computed.
37718 * When setting graph mode to sequence all spatial
37719 * subscriptions are aborted.
37721 * @param {GraphMode} mode - Graph mode to set.
37723 GraphService.prototype.setGraphMode = function (mode) {
37724 if (this._graphMode === mode) {
37727 if (mode === Graph_1.GraphMode.Sequence) {
37728 this._resetSubscriptions(this._spatialSubscriptions);
37730 this._graphMode = mode;
37731 this._graphModeSubject$.next(this._graphMode);
37736 * @description Resets the graph but keeps the nodes of the
37739 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
37740 * @return {Observable<Node>} Observable emitting a single item,
37741 * the graph, when it has been reset.
37743 GraphService.prototype.reset$ = function (keepKeys) {
37744 this._abortSubjects(this._firstGraphSubjects$);
37745 this._resetSubscriptions(this._initializeCacheSubscriptions);
37746 this._resetSubscriptions(this._sequenceSubscriptions);
37747 this._resetSubscriptions(this._spatialSubscriptions);
37748 return this._graph$
37750 .do(function (graph) {
37751 graph.reset(keepKeys);
37753 .map(function (graph) {
37758 * Uncache the graph.
37760 * @description Uncaches the graph by removing tiles, nodes and
37761 * sequences. Keeps the nodes of the supplied keys and the tiles
37762 * related to those nodes.
37764 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
37765 * @param {string} keepSequenceKey - Optional key of sequence
37766 * for which the belonging nodes should not be disposed or
37767 * removed from the graph. These nodes may still be uncached if
37768 * not specified in keep keys param.
37769 * @return {Observable<Graph>} Observable emitting a single item,
37770 * the graph, when the graph has been uncached.
37772 GraphService.prototype.uncache$ = function (keepKeys, keepSequenceKey) {
37773 return this._graph$
37775 .do(function (graph) {
37776 graph.uncache(keepKeys, keepSequenceKey);
37778 .map(function (graph) {
37782 GraphService.prototype._abortSubjects = function (subjects) {
37783 for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
37784 var subject = _a[_i];
37785 this._removeFromArray(subject, subjects);
37786 subject.error(new Error("Cache node request was aborted."));
37789 GraphService.prototype._removeFromArray = function (object, objects) {
37790 var index = objects.indexOf(object);
37791 if (index !== -1) {
37792 objects.splice(index, 1);
37795 GraphService.prototype._resetSubscriptions = function (subscriptions) {
37796 for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
37797 var subscription = _a[_i];
37798 this._removeFromArray(subscription, subscriptions);
37799 if (!subscription.closed) {
37800 subscription.unsubscribe();
37804 return GraphService;
37806 exports.GraphService = GraphService;
37807 exports.default = GraphService;
37809 },{"../Graph":285,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":52,"rxjs/add/operator/concat":54,"rxjs/add/operator/do":59,"rxjs/add/operator/expand":60,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/last":64,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72}],387:[function(require,module,exports){
37811 /// <reference path="../../typings/index.d.ts" />
37812 Object.defineProperty(exports, "__esModule", { value: true });
37813 var Subject_1 = require("rxjs/Subject");
37814 var ImageLoadingService = /** @class */ (function () {
37815 function ImageLoadingService() {
37816 this._loadnode$ = new Subject_1.Subject();
37817 this._loadstatus$ = this._loadnode$
37818 .scan(function (_a, node) {
37820 var changed = false;
37821 if (node.loadStatus.total === 0 || node.loadStatus.loaded === node.loadStatus.total) {
37822 if (node.key in nodes) {
37823 delete nodes[node.key];
37828 nodes[node.key] = node.loadStatus;
37831 return [nodes, changed];
37833 .filter(function (_a) {
37834 var nodes = _a[0], changed = _a[1];
37837 .map(function (_a) {
37843 this._loadstatus$.subscribe(function () { });
37845 Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
37847 return this._loadnode$;
37852 Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
37854 return this._loadstatus$;
37859 return ImageLoadingService;
37861 exports.ImageLoadingService = ImageLoadingService;
37863 },{"rxjs/Subject":34}],388:[function(require,module,exports){
37865 /// <reference path="../../typings/index.d.ts" />
37866 Object.defineProperty(exports, "__esModule", { value: true });
37867 var Pbf = require("pbf");
37868 var MeshReader = /** @class */ (function () {
37869 function MeshReader() {
37871 MeshReader.read = function (buffer) {
37872 var pbf = new Pbf(buffer);
37873 return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
37875 MeshReader._readMeshField = function (tag, mesh, pbf) {
37877 mesh.vertices.push(pbf.readFloat());
37879 else if (tag === 2) {
37880 mesh.faces.push(pbf.readVarint());
37885 exports.MeshReader = MeshReader;
37887 },{"pbf":23}],389:[function(require,module,exports){
37889 Object.defineProperty(exports, "__esModule", { value: true });
37890 require("rxjs/add/observable/combineLatest");
37891 require("rxjs/add/operator/map");
37895 * @classdesc Represents a node in the navigation graph.
37897 * Explanation of position and bearing properties:
37899 * When images are uploaded they will have GPS information in the EXIF, this is what
37900 * is called `originalLatLon`(@link Node#originalLatLon).
37902 * When Structure from Motions has been run for a node a `computedLatLon` that
37903 * differs from the `originalLatLon` will be created. It is different because
37904 * GPS positions are not very exact and SfM aligns the camera positions according
37905 * to the 3D reconstruction (@link Node#computedLatLon).
37907 * At last there exist a `latLon` property which evaluates to
37908 * the `computedLatLon` from SfM if it exists but falls back
37909 * to the `originalLatLon` from the EXIF GPS otherwise (@link Node#latlon).
37911 * Everything that is done in in the Viewer is based on the SfM positions,
37912 * i.e. `computedLatLon`. That is why the smooth transitions go in the right
37913 * direction (nd not in strange directions because of bad GPS).
37915 * E.g. when placing a marker in the Viewer it is relative to the SfM
37916 * position i.e. the `computedLatLon`.
37918 * The same concept as above also applies to the compass angle (or bearing) properties
37919 * `originalCa`, `computedCa` and `ca`.
37921 var Node = /** @class */ (function () {
37923 * Create a new node instance.
37925 * @description Nodes are always created internally by the library.
37926 * Nodes can not be added to the library through any API method.
37928 * @param {ICoreNode} coreNode - Raw core node data.
37930 function Node(core) {
37931 this._cache = null;
37935 Object.defineProperty(Node.prototype, "assetsCached", {
37937 * Get assets cached.
37939 * @description The assets that need to be cached for this property
37940 * to report true are the following: fill properties, image and mesh.
37941 * The library ensures that the current node will always have the
37944 * @returns {boolean} Value indicating whether all assets have been
37948 return this._core != null &&
37949 this._fill != null &&
37950 this._cache != null &&
37951 this._cache.image != null &&
37952 this._cache.mesh != null;
37957 Object.defineProperty(Node.prototype, "alt", {
37961 * @description If SfM has not been run the computed altitude is
37962 * set to a default value of two meters.
37964 * @returns {number} Altitude, in meters.
37967 return this._fill.calt;
37972 Object.defineProperty(Node.prototype, "ca", {
37976 * @description If the SfM computed compass angle exists it will
37977 * be returned, otherwise the original EXIF compass angle.
37979 * @returns {number} Compass angle, measured in degrees.
37982 return this._fill.cca != null ? this._fill.cca : this._fill.ca;
37987 Object.defineProperty(Node.prototype, "capturedAt", {
37991 * @returns {number} Timestamp when the image was captured.
37994 return this._fill.captured_at;
37999 Object.defineProperty(Node.prototype, "computedCA", {
38003 * @description Will not be set if SfM has not been run.
38005 * @returns {number} SfM computed compass angle, measured in degrees.
38008 return this._fill.cca;
38013 Object.defineProperty(Node.prototype, "computedLatLon", {
38015 * Get computedLatLon.
38017 * @description Will not be set if SfM has not been run.
38019 * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
38020 * measured in degrees.
38023 return this._core.cl;
38028 Object.defineProperty(Node.prototype, "focal", {
38032 * @description Will not be set if SfM has not been run.
38034 * @returns {number} SfM computed focal length.
38037 return this._fill.cfocal;
38042 Object.defineProperty(Node.prototype, "full", {
38046 * @description The library ensures that the current node will
38049 * @returns {boolean} Value indicating whether the node has all
38050 * properties filled.
38053 return this._fill != null;
38058 Object.defineProperty(Node.prototype, "fullPano", {
38062 * @returns {boolean} Value indicating whether the node is a complete
38066 return this._fill.gpano != null &&
38067 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
38068 this._fill.gpano.CroppedAreaTopPixels === 0 &&
38069 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
38070 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
38075 Object.defineProperty(Node.prototype, "gpano", {
38079 * @description Will not be set for non panoramic images.
38081 * @returns {IGPano} Panorama information for panorama images.
38084 return this._fill.gpano;
38089 Object.defineProperty(Node.prototype, "height", {
38093 * @returns {number} Height of original image, not adjusted
38097 return this._fill.height;
38102 Object.defineProperty(Node.prototype, "image", {
38106 * @description The image will always be set on the current node.
38108 * @returns {HTMLImageElement} Cached image element of the node.
38111 return this._cache.image;
38116 Object.defineProperty(Node.prototype, "key", {
38120 * @returns {string} Unique key of the node.
38123 return this._core.key;
38128 Object.defineProperty(Node.prototype, "latLon", {
38132 * @description If the SfM computed latitude longitude exist
38133 * it will be returned, otherwise the original EXIF latitude
38136 * @returns {ILatLon} Latitude longitude in WGS84 datum,
38137 * measured in degrees.
38140 return this._core.cl != null ? this._core.cl : this._core.l;
38145 Object.defineProperty(Node.prototype, "loadStatus", {
38149 * @returns {ILoadStatus} Value indicating the load status
38150 * of the mesh and image.
38153 return this._cache.loadStatus;
38158 Object.defineProperty(Node.prototype, "merged", {
38162 * @returns {boolean} Value indicating whether SfM has been
38163 * run on the node and the node has been merged into a
38164 * connected component.
38167 return this._fill != null &&
38168 this._fill.merge_version != null &&
38169 this._fill.merge_version > 0;
38174 Object.defineProperty(Node.prototype, "mergeCC", {
38178 * @description Will not be set if SfM has not yet been run on
38181 * @returns {number} SfM connected component key to which
38185 return this._fill.merge_cc;
38190 Object.defineProperty(Node.prototype, "mergeVersion", {
38192 * Get mergeVersion.
38194 * @returns {number} Version for which SfM was run and image was merged.
38197 return this._fill.merge_version;
38202 Object.defineProperty(Node.prototype, "mesh", {
38206 * @description The mesh will always be set on the current node.
38208 * @returns {IMesh} SfM triangulated mesh of reconstructed
38209 * atomic 3D points.
38212 return this._cache.mesh;
38217 Object.defineProperty(Node.prototype, "orientation", {
38221 * @returns {number} EXIF orientation of original image.
38224 return this._fill.orientation;
38229 Object.defineProperty(Node.prototype, "originalCA", {
38233 * @returns {number} Original EXIF compass angle, measured in
38237 return this._fill.ca;
38242 Object.defineProperty(Node.prototype, "originalLatLon", {
38244 * Get originalLatLon.
38246 * @returns {ILatLon} Original EXIF latitude longitude in
38247 * WGS84 datum, measured in degrees.
38250 return this._core.l;
38255 Object.defineProperty(Node.prototype, "pano", {
38259 * @returns {boolean} Value indicating whether the node is a panorama.
38260 * It could be a cropped or full panorama.
38263 return this._fill.gpano != null &&
38264 this._fill.gpano.FullPanoWidthPixels != null;
38269 Object.defineProperty(Node.prototype, "projectKey", {
38273 * @returns {string} Unique key of the project to which
38274 * the node belongs.
38277 return this._fill.project != null ?
38278 this._fill.project.key :
38284 Object.defineProperty(Node.prototype, "rotation", {
38288 * @description Will not be set if SfM has not been run.
38290 * @returns {Array<number>} Rotation vector in angle axis representation.
38293 return this._fill.c_rotation;
38298 Object.defineProperty(Node.prototype, "scale", {
38302 * @description Will not be set if SfM has not been run.
38304 * @returns {number} Scale of atomic reconstruction.
38307 return this._fill.atomic_scale;
38312 Object.defineProperty(Node.prototype, "sequenceKey", {
38316 * @returns {string} Unique key of the sequence to which
38317 * the node belongs.
38320 return this._core.sequence.key;
38325 Object.defineProperty(Node.prototype, "sequenceEdges", {
38327 * Get sequenceEdges.
38329 * @returns {IEdgeStatus} Value describing the status of the
38333 return this._cache.sequenceEdges;
38338 Object.defineProperty(Node.prototype, "sequenceEdges$", {
38340 * Get sequenceEdges$.
38342 * @returns {Observable<IEdgeStatus>} Observable emitting
38343 * values describing the status of the sequence edges.
38346 return this._cache.sequenceEdges$;
38351 Object.defineProperty(Node.prototype, "spatialEdges", {
38353 * Get spatialEdges.
38355 * @returns {IEdgeStatus} Value describing the status of the
38359 return this._cache.spatialEdges;
38364 Object.defineProperty(Node.prototype, "spatialEdges$", {
38366 * Get spatialEdges$.
38368 * @returns {Observable<IEdgeStatus>} Observable emitting
38369 * values describing the status of the spatial edges.
38372 return this._cache.spatialEdges$;
38377 Object.defineProperty(Node.prototype, "userKey", {
38381 * @returns {string} Unique key of the user who uploaded
38385 return this._fill.user.key;
38390 Object.defineProperty(Node.prototype, "username", {
38394 * @returns {string} Username of the user who uploaded
38398 return this._fill.user.username;
38403 Object.defineProperty(Node.prototype, "width", {
38407 * @returns {number} Width of original image, not
38408 * adjusted for orientation.
38411 return this._fill.width;
38417 * Cache the image and mesh assets.
38419 * @description The assets are always cached internally by the
38420 * library prior to setting a node as the current node.
38422 * @returns {Observable<Node>} Observable emitting this node whenever the
38423 * load status has changed and when the mesh or image has been fully loaded.
38425 Node.prototype.cacheAssets$ = function () {
38427 return this._cache.cacheAssets$(this.key, this.pano, this.merged)
38428 .map(function (cache) {
38432 Node.prototype.cacheImage$ = function (imageSize) {
38434 return this._cache.cacheImage$(this.key, imageSize)
38435 .map(function (cache) {
38440 * Cache the sequence edges.
38442 * @description The sequence edges are cached asynchronously
38443 * internally by the library.
38445 * @param {Array<IEdge>} edges - Sequence edges to cache.
38447 Node.prototype.cacheSequenceEdges = function (edges) {
38448 this._cache.cacheSequenceEdges(edges);
38451 * Cache the spatial edges.
38453 * @description The spatial edges are cached asynchronously
38454 * internally by the library.
38456 * @param {Array<IEdge>} edges - Spatial edges to cache.
38458 Node.prototype.cacheSpatialEdges = function (edges) {
38459 this._cache.cacheSpatialEdges(edges);
38462 * Dispose the node.
38464 * @description Disposes all cached assets.
38466 Node.prototype.dispose = function () {
38467 if (this._cache != null) {
38468 this._cache.dispose();
38469 this._cache = null;
38475 * Initialize the node cache.
38477 * @description The node cache is initialized internally by
38480 * @param {NodeCache} cache - The node cache to set as cache.
38482 Node.prototype.initializeCache = function (cache) {
38483 if (this._cache != null) {
38484 throw new Error("Node cache already initialized (" + this.key + ").");
38486 this._cache = cache;
38489 * Fill the node with all properties.
38491 * @description The node is filled internally by
38494 * @param {IFillNode} fill - The fill node struct.
38496 Node.prototype.makeFull = function (fill) {
38497 if (fill == null) {
38498 throw new Error("Fill can not be null.");
38503 * Reset the sequence edges.
38505 Node.prototype.resetSequenceEdges = function () {
38506 this._cache.resetSequenceEdges();
38509 * Reset the spatial edges.
38511 Node.prototype.resetSpatialEdges = function () {
38512 this._cache.resetSpatialEdges();
38515 * Clears the image and mesh assets, aborts
38516 * any outstanding requests and resets edges.
38518 Node.prototype.uncache = function () {
38519 if (this._cache == null) {
38522 this._cache.dispose();
38523 this._cache = null;
38527 exports.Node = Node;
38528 exports.default = Node;
38530 },{"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/map":65}],390:[function(require,module,exports){
38531 (function (Buffer){
38533 Object.defineProperty(exports, "__esModule", { value: true });
38534 var Subject_1 = require("rxjs/Subject");
38535 var Observable_1 = require("rxjs/Observable");
38536 require("rxjs/add/observable/combineLatest");
38537 require("rxjs/add/operator/publishReplay");
38538 var Graph_1 = require("../Graph");
38539 var Utils_1 = require("../Utils");
38543 * @classdesc Represents the cached properties of a node.
38545 var NodeCache = /** @class */ (function () {
38547 * Create a new node cache instance.
38549 function NodeCache() {
38550 this._disposed = false;
38551 this._image = null;
38552 this._loadStatus = { loaded: 0, total: 0 };
38554 this._sequenceEdges = { cached: false, edges: [] };
38555 this._spatialEdges = { cached: false, edges: [] };
38556 this._sequenceEdgesChanged$ = new Subject_1.Subject();
38557 this._sequenceEdges$ = this._sequenceEdgesChanged$
38558 .startWith(this._sequenceEdges)
38561 this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
38562 this._spatialEdgesChanged$ = new Subject_1.Subject();
38563 this._spatialEdges$ = this._spatialEdgesChanged$
38564 .startWith(this._spatialEdges)
38567 this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
38568 this._cachingAssets$ = null;
38570 Object.defineProperty(NodeCache.prototype, "image", {
38574 * @description Will not be set when assets have not been cached
38575 * or when the object has been disposed.
38577 * @returns {HTMLImageElement} Cached image element of the node.
38580 return this._image;
38585 Object.defineProperty(NodeCache.prototype, "loadStatus", {
38589 * @returns {ILoadStatus} Value indicating the load status
38590 * of the mesh and image.
38593 return this._loadStatus;
38598 Object.defineProperty(NodeCache.prototype, "mesh", {
38602 * @description Will not be set when assets have not been cached
38603 * or when the object has been disposed.
38605 * @returns {IMesh} SfM triangulated mesh of reconstructed
38606 * atomic 3D points.
38614 Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
38616 * Get sequenceEdges.
38618 * @returns {IEdgeStatus} Value describing the status of the
38622 return this._sequenceEdges;
38627 Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
38629 * Get sequenceEdges$.
38631 * @returns {Observable<IEdgeStatus>} Observable emitting
38632 * values describing the status of the sequence edges.
38635 return this._sequenceEdges$;
38640 Object.defineProperty(NodeCache.prototype, "spatialEdges", {
38642 * Get spatialEdges.
38644 * @returns {IEdgeStatus} Value describing the status of the
38648 return this._spatialEdges;
38653 Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
38655 * Get spatialEdges$.
38657 * @returns {Observable<IEdgeStatus>} Observable emitting
38658 * values describing the status of the spatial edges.
38661 return this._spatialEdges$;
38667 * Cache the image and mesh assets.
38669 * @param {string} key - Key of the node to cache.
38670 * @param {boolean} pano - Value indicating whether node is a panorama.
38671 * @param {boolean} merged - Value indicating whether node is merged.
38672 * @returns {Observable<NodeCache>} Observable emitting this node
38673 * cache whenever the load status has changed and when the mesh or image
38674 * has been fully loaded.
38676 NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
38678 if (this._cachingAssets$ != null) {
38679 return this._cachingAssets$;
38681 var imageSize = pano ?
38682 Utils_1.Settings.basePanoramaSize :
38683 Utils_1.Settings.baseImageSize;
38684 this._cachingAssets$ = Observable_1.Observable
38685 .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
38686 _this._loadStatus.loaded = 0;
38687 _this._loadStatus.total = 0;
38689 _this._mesh = meshStatus.object;
38690 _this._loadStatus.loaded += meshStatus.loaded.loaded;
38691 _this._loadStatus.total += meshStatus.loaded.total;
38694 _this._image = imageStatus.object;
38695 _this._loadStatus.loaded += imageStatus.loaded.loaded;
38696 _this._loadStatus.total += imageStatus.loaded.total;
38700 .finally(function () {
38701 _this._cachingAssets$ = null;
38705 return this._cachingAssets$;
38708 * Cache an image with a higher resolution than the current one.
38710 * @param {string} key - Key of the node to cache.
38711 * @param {ImageSize} imageSize - The size to cache.
38712 * @returns {Observable<NodeCache>} Observable emitting a single item,
38713 * the node cache, when the image has been cached. If supplied image
38714 * size is not larger than the current image size the node cache is
38715 * returned immediately.
38717 NodeCache.prototype.cacheImage$ = function (key, imageSize) {
38719 if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
38720 return Observable_1.Observable.of(this);
38722 return this._cacheImage$(key, imageSize)
38723 .first(function (status) {
38724 return status.object != null;
38726 .do(function (status) {
38727 _this._disposeImage();
38728 _this._image = status.object;
38730 .map(function (imageStatus) {
38735 * Cache the sequence edges.
38737 * @param {Array<IEdge>} edges - Sequence edges to cache.
38739 NodeCache.prototype.cacheSequenceEdges = function (edges) {
38740 this._sequenceEdges = { cached: true, edges: edges };
38741 this._sequenceEdgesChanged$.next(this._sequenceEdges);
38744 * Cache the spatial edges.
38746 * @param {Array<IEdge>} edges - Spatial edges to cache.
38748 NodeCache.prototype.cacheSpatialEdges = function (edges) {
38749 this._spatialEdges = { cached: true, edges: edges };
38750 this._spatialEdgesChanged$.next(this._spatialEdges);
38753 * Dispose the node cache.
38755 * @description Disposes all cached assets and unsubscribes to
38758 NodeCache.prototype.dispose = function () {
38759 this._sequenceEdgesSubscription.unsubscribe();
38760 this._spatialEdgesSubscription.unsubscribe();
38761 this._disposeImage();
38763 this._loadStatus.loaded = 0;
38764 this._loadStatus.total = 0;
38765 this._sequenceEdges = { cached: false, edges: [] };
38766 this._spatialEdges = { cached: false, edges: [] };
38767 this._sequenceEdgesChanged$.next(this._sequenceEdges);
38768 this._spatialEdgesChanged$.next(this._spatialEdges);
38769 this._disposed = true;
38770 if (this._imageRequest != null) {
38771 this._imageRequest.abort();
38773 if (this._meshRequest != null) {
38774 this._meshRequest.abort();
38778 * Reset the sequence edges.
38780 NodeCache.prototype.resetSequenceEdges = function () {
38781 this._sequenceEdges = { cached: false, edges: [] };
38782 this._sequenceEdgesChanged$.next(this._sequenceEdges);
38785 * Reset the spatial edges.
38787 NodeCache.prototype.resetSpatialEdges = function () {
38788 this._spatialEdges = { cached: false, edges: [] };
38789 this._spatialEdgesChanged$.next(this._spatialEdges);
38794 * @param {string} key - Key of the node to cache.
38795 * @param {boolean} pano - Value indicating whether node is a panorama.
38796 * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
38797 * emitting a load status object every time the load status changes
38798 * and completes when the image is fully loaded.
38800 NodeCache.prototype._cacheImage$ = function (key, imageSize) {
38802 return Observable_1.Observable.create(function (subscriber) {
38803 var xmlHTTP = new XMLHttpRequest();
38804 xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
38805 xmlHTTP.responseType = "arraybuffer";
38806 xmlHTTP.timeout = 15000;
38807 xmlHTTP.onload = function (pe) {
38808 if (xmlHTTP.status !== 200) {
38809 _this._imageRequest = null;
38810 subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
38813 var image = new Image();
38814 image.crossOrigin = "Anonymous";
38815 image.onload = function (e) {
38816 _this._imageRequest = null;
38817 if (_this._disposed) {
38818 window.URL.revokeObjectURL(image.src);
38819 subscriber.error(new Error("Image load was aborted (" + key + ")"));
38822 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
38823 subscriber.complete();
38825 image.onerror = function (error) {
38826 _this._imageRequest = null;
38827 subscriber.error(new Error("Failed to load image (" + key + ")"));
38829 var blob = new Blob([xmlHTTP.response]);
38830 image.src = window.URL.createObjectURL(blob);
38832 xmlHTTP.onprogress = function (pe) {
38833 if (_this._disposed) {
38836 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
38838 xmlHTTP.onerror = function (error) {
38839 _this._imageRequest = null;
38840 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
38842 xmlHTTP.ontimeout = function (e) {
38843 _this._imageRequest = null;
38844 subscriber.error(new Error("Image request timed out (" + key + ")"));
38846 xmlHTTP.onabort = function (event) {
38847 _this._imageRequest = null;
38848 subscriber.error(new Error("Image request was aborted (" + key + ")"));
38850 _this._imageRequest = xmlHTTP;
38851 xmlHTTP.send(null);
38857 * @param {string} key - Key of the node to cache.
38858 * @param {boolean} merged - Value indicating whether node is merged.
38859 * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
38860 * a load status object every time the load status changes and completes
38861 * when the mesh is fully loaded.
38863 NodeCache.prototype._cacheMesh$ = function (key, merged) {
38865 return Observable_1.Observable.create(function (subscriber) {
38867 subscriber.next(_this._createEmptyMeshLoadStatus());
38868 subscriber.complete();
38871 var xmlHTTP = new XMLHttpRequest();
38872 xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
38873 xmlHTTP.responseType = "arraybuffer";
38874 xmlHTTP.timeout = 15000;
38875 xmlHTTP.onload = function (pe) {
38876 _this._meshRequest = null;
38877 if (_this._disposed) {
38880 var mesh = xmlHTTP.status === 200 ?
38881 Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
38882 { faces: [], vertices: [] };
38883 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
38884 subscriber.complete();
38886 xmlHTTP.onprogress = function (pe) {
38887 if (_this._disposed) {
38890 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
38892 xmlHTTP.onerror = function (e) {
38893 _this._meshRequest = null;
38894 console.error("Failed to cache mesh (" + key + ")");
38895 subscriber.next(_this._createEmptyMeshLoadStatus());
38896 subscriber.complete();
38898 xmlHTTP.ontimeout = function (e) {
38899 _this._meshRequest = null;
38900 console.error("Mesh request timed out (" + key + ")");
38901 subscriber.next(_this._createEmptyMeshLoadStatus());
38902 subscriber.complete();
38904 xmlHTTP.onabort = function (e) {
38905 _this._meshRequest = null;
38906 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
38908 _this._meshRequest = xmlHTTP;
38909 xmlHTTP.send(null);
38913 * Create a load status object with an empty mesh.
38915 * @returns {ILoadStatusObject<IMesh>} Load status object
38918 NodeCache.prototype._createEmptyMeshLoadStatus = function () {
38920 loaded: { loaded: 0, total: 0 },
38921 object: { faces: [], vertices: [] },
38924 NodeCache.prototype._disposeImage = function () {
38925 if (this._image != null) {
38926 window.URL.revokeObjectURL(this._image.src);
38928 this._image = null;
38932 exports.NodeCache = NodeCache;
38933 exports.default = NodeCache;
38935 }).call(this,require("buffer").Buffer)
38937 },{"../Graph":285,"../Utils":291,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/publishReplay":72}],391:[function(require,module,exports){
38939 /// <reference path="../../typings/index.d.ts" />
38940 Object.defineProperty(exports, "__esModule", { value: true });
38941 var _ = require("underscore");
38945 * @classdesc Represents a sequence of ordered nodes.
38947 var Sequence = /** @class */ (function () {
38949 * Create a new sequene instance.
38951 * @param {ISequence} sequence - Raw sequence data.
38953 function Sequence(sequence) {
38954 this._key = sequence.key;
38955 this._keys = sequence.keys;
38957 Object.defineProperty(Sequence.prototype, "key", {
38961 * @returns {string} Unique sequence key.
38969 Object.defineProperty(Sequence.prototype, "keys", {
38973 * @returns {Array<string>} Array of ordered node keys in the sequence.
38982 * Dispose the sequence.
38984 * @description Disposes all cached assets.
38986 Sequence.prototype.dispose = function () {
38991 * Find the next node key in the sequence with respect to
38992 * the provided node key.
38994 * @param {string} key - Reference node key.
38995 * @returns {string} Next key in sequence if it exists, null otherwise.
38997 Sequence.prototype.findNextKey = function (key) {
38998 var i = _.indexOf(this._keys, key);
38999 if ((i + 1) >= this._keys.length || i === -1) {
39003 return this._keys[i + 1];
39007 * Find the previous node key in the sequence with respect to
39008 * the provided node key.
39010 * @param {string} key - Reference node key.
39011 * @returns {string} Previous key in sequence if it exists, null otherwise.
39013 Sequence.prototype.findPrevKey = function (key) {
39014 var i = _.indexOf(this._keys, key);
39015 if (i === 0 || i === -1) {
39019 return this._keys[i - 1];
39024 exports.Sequence = Sequence;
39025 exports.default = Sequence;
39027 },{"underscore":233}],392:[function(require,module,exports){
39029 /// <reference path="../../../typings/index.d.ts" />
39030 Object.defineProperty(exports, "__esModule", { value: true });
39031 var THREE = require("three");
39032 var Edge_1 = require("../../Edge");
39033 var Error_1 = require("../../Error");
39034 var Geo_1 = require("../../Geo");
39036 * @class EdgeCalculator
39038 * @classdesc Represents a class for calculating node edges.
39040 var EdgeCalculator = /** @class */ (function () {
39042 * Create a new edge calculator instance.
39044 * @param {EdgeCalculatorSettings} settings - Settings struct.
39045 * @param {EdgeCalculatorDirections} directions - Directions struct.
39046 * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
39048 function EdgeCalculator(settings, directions, coefficients) {
39049 this._spatial = new Geo_1.Spatial();
39050 this._geoCoords = new Geo_1.GeoCoords();
39051 this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
39052 this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
39053 this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
39056 * Returns the potential edges to destination nodes for a set
39057 * of nodes with respect to a source node.
39059 * @param {Node} node - Source node.
39060 * @param {Array<Node>} nodes - Potential destination nodes.
39061 * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
39062 * be returned even if they do not meet the criteria for a potential edge.
39063 * @throws {ArgumentMapillaryError} If node is not full.
39065 EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
39067 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39069 if (!node.merged) {
39072 var currentDirection = this._spatial.viewingDirection(node.rotation);
39073 var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
39074 var potentialEdges = [];
39075 for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
39076 var potential = potentialNodes_1[_i];
39077 if (!potential.merged ||
39078 potential.key === node.key) {
39081 var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
39082 var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
39083 var distance = motion.length();
39084 if (distance > this._settings.maxDistance &&
39085 fallbackKeys.indexOf(potential.key) < 0) {
39088 var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
39089 var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
39090 var direction = this._spatial.viewingDirection(potential.rotation);
39091 var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
39092 var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
39093 var verticalDirectionChange = verticalDirection - currentVerticalDirection;
39094 var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
39095 var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
39096 var sameSequence = potential.sequenceKey != null &&
39097 node.sequenceKey != null &&
39098 potential.sequenceKey === node.sequenceKey;
39099 var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
39100 potential.mergeCC === node.mergeCC;
39101 var sameUser = potential.userKey === node.userKey;
39102 var potentialEdge = {
39103 capturedAt: potential.capturedAt,
39104 croppedPano: potential.pano && !potential.fullPano,
39105 directionChange: directionChange,
39106 distance: distance,
39107 fullPano: potential.fullPano,
39108 key: potential.key,
39109 motionChange: motionChange,
39110 rotation: rotation,
39111 sameMergeCC: sameMergeCC,
39112 sameSequence: sameSequence,
39113 sameUser: sameUser,
39114 sequenceKey: potential.sequenceKey,
39115 verticalDirectionChange: verticalDirectionChange,
39116 verticalMotion: verticalMotion,
39117 worldMotionAzimuth: worldMotionAzimuth,
39119 potentialEdges.push(potentialEdge);
39121 return potentialEdges;
39124 * Computes the sequence edges for a node.
39126 * @param {Node} node - Source node.
39127 * @throws {ArgumentMapillaryError} If node is not full.
39129 EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
39131 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39133 if (node.sequenceKey !== sequence.key) {
39134 throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
39137 var nextKey = sequence.findNextKey(node.key);
39138 if (nextKey != null) {
39141 direction: Edge_1.EdgeDirection.Next,
39142 worldMotionAzimuth: Number.NaN,
39148 var prevKey = sequence.findPrevKey(node.key);
39149 if (prevKey != null) {
39152 direction: Edge_1.EdgeDirection.Prev,
39153 worldMotionAzimuth: Number.NaN,
39162 * Computes the similar edges for a node.
39164 * @description Similar edges for perspective images and cropped panoramas
39165 * look roughly in the same direction and are positioned closed to the node.
39166 * Similar edges for full panoramas only target other full panoramas.
39168 * @param {Node} node - Source node.
39169 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
39170 * @throws {ArgumentMapillaryError} If node is not full.
39172 EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
39175 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39177 var nodeFullPano = node.fullPano;
39178 var sequenceGroups = {};
39179 for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
39180 var potentialEdge = potentialEdges_1[_i];
39181 if (potentialEdge.sequenceKey == null) {
39184 if (potentialEdge.sameSequence ||
39185 !potentialEdge.sameMergeCC) {
39188 if (nodeFullPano) {
39189 if (!potentialEdge.fullPano) {
39194 if (!potentialEdge.fullPano &&
39195 Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
39199 if (potentialEdge.distance > this._settings.similarMaxDistance) {
39202 if (potentialEdge.sameUser &&
39203 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
39204 this._settings.similarMinTimeDifference) {
39207 if (sequenceGroups[potentialEdge.sequenceKey] == null) {
39208 sequenceGroups[potentialEdge.sequenceKey] = [];
39210 sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
39212 var similarEdges = [];
39213 var calculateScore = node.fullPano ?
39214 function (potentialEdge) {
39215 return potentialEdge.distance;
39217 function (potentialEdge) {
39218 return _this._coefficients.similarDistance * potentialEdge.distance +
39219 _this._coefficients.similarRotation * potentialEdge.rotation;
39221 for (var sequenceKey in sequenceGroups) {
39222 if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
39225 var lowestScore = Number.MAX_VALUE;
39226 var similarEdge = null;
39227 for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
39228 var potentialEdge = _b[_a];
39229 var score = calculateScore(potentialEdge);
39230 if (score < lowestScore) {
39231 lowestScore = score;
39232 similarEdge = potentialEdge;
39235 if (similarEdge == null) {
39238 similarEdges.push(similarEdge);
39240 return similarEdges
39241 .map(function (potentialEdge) {
39244 direction: Edge_1.EdgeDirection.Similar,
39245 worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
39248 to: potentialEdge.key,
39253 * Computes the step edges for a perspective node.
39255 * @description Step edge targets can only be other perspective nodes.
39256 * Returns an empty array for cropped and full panoramas.
39258 * @param {Node} node - Source node.
39259 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
39260 * @param {string} prevKey - Key of previous node in sequence.
39261 * @param {string} prevKey - Key of next node in sequence.
39262 * @throws {ArgumentMapillaryError} If node is not full.
39264 EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
39266 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39272 for (var k in this._directions.steps) {
39273 if (!this._directions.steps.hasOwnProperty(k)) {
39276 var step = this._directions.steps[k];
39277 var lowestScore = Number.MAX_VALUE;
39279 var fallback = null;
39280 for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
39281 var potential = potentialEdges_2[_i];
39282 if (potential.croppedPano || potential.fullPano) {
39285 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
39288 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
39289 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
39290 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
39291 if (Math.abs(drift) > this._settings.stepMaxDrift) {
39294 var potentialKey = potential.key;
39295 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
39296 fallback = potential;
39298 if (potential.distance > this._settings.stepMaxDistance) {
39301 motionDifference = Math.sqrt(motionDifference * motionDifference +
39302 potential.verticalMotion * potential.verticalMotion);
39303 var score = this._coefficients.stepPreferredDistance *
39304 Math.abs(potential.distance - this._settings.stepPreferredDistance) /
39305 this._settings.stepMaxDistance +
39306 this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
39307 this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
39308 this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
39309 this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
39310 if (score < lowestScore) {
39311 lowestScore = score;
39315 edge = edge == null ? fallback : edge;
39316 if (edge != null) {
39319 direction: step.direction,
39320 worldMotionAzimuth: edge.worldMotionAzimuth,
39330 * Computes the turn edges for a perspective node.
39332 * @description Turn edge targets can only be other perspective images.
39333 * Returns an empty array for cropped and full panoramas.
39335 * @param {Node} node - Source node.
39336 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
39337 * @throws {ArgumentMapillaryError} If node is not full.
39339 EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
39341 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39347 for (var k in this._directions.turns) {
39348 if (!this._directions.turns.hasOwnProperty(k)) {
39351 var turn = this._directions.turns[k];
39352 var lowestScore = Number.MAX_VALUE;
39354 for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
39355 var potential = potentialEdges_3[_i];
39356 if (potential.croppedPano || potential.fullPano) {
39359 if (potential.distance > this._settings.turnMaxDistance) {
39362 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
39363 potential.distance < this._settings.turnMaxRigDistance &&
39364 Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
39365 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
39366 var score = void 0;
39368 potential.directionChange * turn.directionChange > 0 &&
39369 Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
39370 score = -Math.PI / 2 + Math.abs(potential.directionChange);
39373 if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
39376 var motionDifference = turn.motionChange ?
39377 this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
39378 motionDifference = Math.sqrt(motionDifference * motionDifference +
39379 potential.verticalMotion * potential.verticalMotion);
39381 this._coefficients.turnDistance * potential.distance /
39382 this._settings.turnMaxDistance +
39383 this._coefficients.turnMotion * motionDifference / Math.PI +
39384 this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
39385 this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
39387 if (score < lowestScore) {
39388 lowestScore = score;
39392 if (edge != null) {
39395 direction: turn.direction,
39396 worldMotionAzimuth: edge.worldMotionAzimuth,
39406 * Computes the pano edges for a perspective node.
39408 * @description Perspective to pano edge targets can only be
39409 * full pano nodes. Returns an empty array for cropped and full panoramas.
39411 * @param {Node} node - Source node.
39412 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
39413 * @throws {ArgumentMapillaryError} If node is not full.
39415 EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
39417 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39422 var lowestScore = Number.MAX_VALUE;
39424 for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
39425 var potential = potentialEdges_4[_i];
39426 if (!potential.fullPano) {
39429 var score = this._coefficients.panoPreferredDistance *
39430 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
39431 this._settings.panoMaxDistance +
39432 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
39433 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
39434 if (score < lowestScore) {
39435 lowestScore = score;
39439 if (edge == null) {
39445 direction: Edge_1.EdgeDirection.Pano,
39446 worldMotionAzimuth: edge.worldMotionAzimuth,
39454 * Computes the full pano and step edges for a full pano node.
39456 * @description Pano to pano edge targets can only be
39457 * full pano nodes. Pano to step edge targets can only be perspective
39459 * Returns an empty array for cropped panoramas and perspective nodes.
39461 * @param {Node} node - Source node.
39462 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
39463 * @throws {ArgumentMapillaryError} If node is not full.
39465 EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
39467 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39469 if (!node.fullPano) {
39472 var panoEdges = [];
39473 var potentialPanos = [];
39474 var potentialSteps = [];
39475 for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
39476 var potential = potentialEdges_5[_i];
39477 if (potential.distance > this._settings.panoMaxDistance) {
39480 if (potential.fullPano) {
39481 if (potential.distance < this._settings.panoMinDistance) {
39484 potentialPanos.push(potential);
39487 if (potential.croppedPano) {
39490 for (var k in this._directions.panos) {
39491 if (!this._directions.panos.hasOwnProperty(k)) {
39494 var pano = this._directions.panos[k];
39495 var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
39496 var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
39497 if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
39500 potentialSteps.push([pano.direction, potential]);
39501 // break if step direction found
39506 var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
39507 var occupiedAngles = [];
39508 var stepAngles = [];
39509 for (var index = 0; index < this._settings.panoMaxItems; index++) {
39510 var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
39511 var lowestScore = Number.MAX_VALUE;
39513 for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
39514 var potential = potentialPanos_1[_a];
39515 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
39516 if (Math.abs(motionDifference) > maxRotationDifference) {
39519 var occupiedDifference = Number.MAX_VALUE;
39520 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
39521 var occupiedAngle = occupiedAngles_1[_b];
39522 var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
39523 if (difference < occupiedDifference) {
39524 occupiedDifference = difference;
39527 if (occupiedDifference <= maxRotationDifference) {
39530 var score = this._coefficients.panoPreferredDistance *
39531 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
39532 this._settings.panoMaxDistance +
39533 this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
39534 this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
39535 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
39536 if (score < lowestScore) {
39537 lowestScore = score;
39541 if (edge != null) {
39542 occupiedAngles.push(edge.motionChange);
39545 direction: Edge_1.EdgeDirection.Pano,
39546 worldMotionAzimuth: edge.worldMotionAzimuth,
39553 stepAngles.push(rotation);
39556 var occupiedStepAngles = {};
39557 occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
39558 occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
39559 occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
39560 occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
39561 occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
39562 for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
39563 var stepAngle = stepAngles_1[_c];
39564 var occupations = [];
39565 for (var k in this._directions.panos) {
39566 if (!this._directions.panos.hasOwnProperty(k)) {
39569 var pano = this._directions.panos[k];
39570 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
39571 .concat(occupiedStepAngles[pano.direction])
39572 .concat(occupiedStepAngles[pano.prev])
39573 .concat(occupiedStepAngles[pano.next]);
39574 var lowestScore = Number.MAX_VALUE;
39576 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
39577 var potential = potentialSteps_1[_d];
39578 if (potential[0] !== pano.direction) {
39581 var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
39582 if (Math.abs(motionChange) > maxRotationDifference) {
39585 var minOccupiedDifference = Number.MAX_VALUE;
39586 for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
39587 var occupiedAngle = allOccupiedAngles_1[_e];
39588 var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
39589 if (occupiedDifference < minOccupiedDifference) {
39590 minOccupiedDifference = occupiedDifference;
39593 if (minOccupiedDifference <= maxRotationDifference) {
39596 var score = this._coefficients.panoPreferredDistance *
39597 Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
39598 this._settings.panoMaxDistance +
39599 this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
39600 this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
39601 if (score < lowestScore) {
39602 lowestScore = score;
39606 if (edge != null) {
39607 occupations.push(edge);
39610 direction: edge[0],
39611 worldMotionAzimuth: edge[1].worldMotionAzimuth,
39618 for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
39619 var occupation = occupations_1[_f];
39620 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
39625 return EdgeCalculator;
39627 exports.EdgeCalculator = EdgeCalculator;
39628 exports.default = EdgeCalculator;
39630 },{"../../Edge":282,"../../Error":283,"../../Geo":284,"three":231}],393:[function(require,module,exports){
39632 Object.defineProperty(exports, "__esModule", { value: true });
39633 var EdgeCalculatorCoefficients = /** @class */ (function () {
39634 function EdgeCalculatorCoefficients() {
39635 this.panoPreferredDistance = 2;
39636 this.panoMotion = 2;
39637 this.panoSequencePenalty = 1;
39638 this.panoMergeCCPenalty = 4;
39639 this.stepPreferredDistance = 4;
39640 this.stepMotion = 3;
39641 this.stepRotation = 4;
39642 this.stepSequencePenalty = 2;
39643 this.stepMergeCCPenalty = 6;
39644 this.similarDistance = 2;
39645 this.similarRotation = 3;
39646 this.turnDistance = 4;
39647 this.turnMotion = 2;
39648 this.turnSequencePenalty = 1;
39649 this.turnMergeCCPenalty = 4;
39651 return EdgeCalculatorCoefficients;
39653 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
39654 exports.default = EdgeCalculatorCoefficients;
39656 },{}],394:[function(require,module,exports){
39658 Object.defineProperty(exports, "__esModule", { value: true });
39659 var Edge_1 = require("../../Edge");
39660 var EdgeCalculatorDirections = /** @class */ (function () {
39661 function EdgeCalculatorDirections() {
39665 this.steps[Edge_1.EdgeDirection.StepForward] = {
39666 direction: Edge_1.EdgeDirection.StepForward,
39670 this.steps[Edge_1.EdgeDirection.StepBackward] = {
39671 direction: Edge_1.EdgeDirection.StepBackward,
39672 motionChange: Math.PI,
39675 this.steps[Edge_1.EdgeDirection.StepLeft] = {
39676 direction: Edge_1.EdgeDirection.StepLeft,
39677 motionChange: Math.PI / 2,
39678 useFallback: false,
39680 this.steps[Edge_1.EdgeDirection.StepRight] = {
39681 direction: Edge_1.EdgeDirection.StepRight,
39682 motionChange: -Math.PI / 2,
39683 useFallback: false,
39685 this.turns[Edge_1.EdgeDirection.TurnLeft] = {
39686 direction: Edge_1.EdgeDirection.TurnLeft,
39687 directionChange: Math.PI / 2,
39688 motionChange: Math.PI / 4,
39690 this.turns[Edge_1.EdgeDirection.TurnRight] = {
39691 direction: Edge_1.EdgeDirection.TurnRight,
39692 directionChange: -Math.PI / 2,
39693 motionChange: -Math.PI / 4,
39695 this.turns[Edge_1.EdgeDirection.TurnU] = {
39696 direction: Edge_1.EdgeDirection.TurnU,
39697 directionChange: Math.PI,
39698 motionChange: null,
39700 this.panos[Edge_1.EdgeDirection.StepForward] = {
39701 direction: Edge_1.EdgeDirection.StepForward,
39702 directionChange: 0,
39703 next: Edge_1.EdgeDirection.StepLeft,
39704 prev: Edge_1.EdgeDirection.StepRight,
39706 this.panos[Edge_1.EdgeDirection.StepBackward] = {
39707 direction: Edge_1.EdgeDirection.StepBackward,
39708 directionChange: Math.PI,
39709 next: Edge_1.EdgeDirection.StepRight,
39710 prev: Edge_1.EdgeDirection.StepLeft,
39712 this.panos[Edge_1.EdgeDirection.StepLeft] = {
39713 direction: Edge_1.EdgeDirection.StepLeft,
39714 directionChange: Math.PI / 2,
39715 next: Edge_1.EdgeDirection.StepBackward,
39716 prev: Edge_1.EdgeDirection.StepForward,
39718 this.panos[Edge_1.EdgeDirection.StepRight] = {
39719 direction: Edge_1.EdgeDirection.StepRight,
39720 directionChange: -Math.PI / 2,
39721 next: Edge_1.EdgeDirection.StepForward,
39722 prev: Edge_1.EdgeDirection.StepBackward,
39725 return EdgeCalculatorDirections;
39727 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
39729 },{"../../Edge":282}],395:[function(require,module,exports){
39731 Object.defineProperty(exports, "__esModule", { value: true });
39732 var EdgeCalculatorSettings = /** @class */ (function () {
39733 function EdgeCalculatorSettings() {
39734 this.panoMinDistance = 0.1;
39735 this.panoMaxDistance = 20;
39736 this.panoPreferredDistance = 5;
39737 this.panoMaxItems = 4;
39738 this.panoMaxStepTurnChange = Math.PI / 8;
39739 this.rotationMaxDistance = this.turnMaxRigDistance;
39740 this.rotationMaxDirectionChange = Math.PI / 6;
39741 this.rotationMaxVerticalDirectionChange = Math.PI / 8;
39742 this.similarMaxDirectionChange = Math.PI / 8;
39743 this.similarMaxDistance = 12;
39744 this.similarMinTimeDifference = 12 * 3600 * 1000;
39745 this.stepMaxDistance = 20;
39746 this.stepMaxDirectionChange = Math.PI / 6;
39747 this.stepMaxDrift = Math.PI / 6;
39748 this.stepPreferredDistance = 4;
39749 this.turnMaxDistance = 15;
39750 this.turnMaxDirectionChange = 2 * Math.PI / 9;
39751 this.turnMaxRigDistance = 0.65;
39752 this.turnMinRigDirectionChange = Math.PI / 6;
39754 Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
39756 return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
39761 return EdgeCalculatorSettings;
39763 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
39764 exports.default = EdgeCalculatorSettings;
39766 },{}],396:[function(require,module,exports){
39768 Object.defineProperty(exports, "__esModule", { value: true });
39770 * Enumeration for edge directions
39773 * @description Directions for edges in node graph describing
39774 * sequence, spatial and node type relations between nodes.
39777 (function (EdgeDirection) {
39779 * Next node in the sequence.
39781 EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
39783 * Previous node in the sequence.
39785 EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
39787 * Step to the left keeping viewing direction.
39789 EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
39791 * Step to the right keeping viewing direction.
39793 EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
39795 * Step forward keeping viewing direction.
39797 EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
39799 * Step backward keeping viewing direction.
39801 EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
39803 * Turn 90 degrees counter clockwise.
39805 EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
39807 * Turn 90 degrees clockwise.
39809 EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
39811 * Turn 180 degrees.
39813 EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
39815 * Panorama in general direction.
39817 EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
39819 * Looking in roughly the same direction at rougly the same position.
39821 EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
39822 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
39824 },{}],397:[function(require,module,exports){
39826 /// <reference path="../../typings/index.d.ts" />
39827 Object.defineProperty(exports, "__esModule", { value: true });
39828 var _ = require("underscore");
39829 var vd = require("virtual-dom");
39830 var Subject_1 = require("rxjs/Subject");
39831 require("rxjs/add/operator/combineLatest");
39832 require("rxjs/add/operator/distinctUntilChanged");
39833 require("rxjs/add/operator/filter");
39834 require("rxjs/add/operator/map");
39835 require("rxjs/add/operator/pluck");
39836 require("rxjs/add/operator/scan");
39837 var Render_1 = require("../Render");
39838 var DOMRenderer = /** @class */ (function () {
39839 function DOMRenderer(element, renderService, currentFrame$) {
39840 this._adaptiveOperation$ = new Subject_1.Subject();
39841 this._render$ = new Subject_1.Subject();
39842 this._renderAdaptive$ = new Subject_1.Subject();
39843 this._renderService = renderService;
39844 this._currentFrame$ = currentFrame$;
39845 var rootNode = vd.create(vd.h("div.domRenderer", []));
39846 element.appendChild(rootNode);
39847 this._offset$ = this._adaptiveOperation$
39848 .scan(function (adaptive, operation) {
39849 return operation(adaptive);
39851 elementHeight: element.offsetHeight,
39852 elementWidth: element.offsetWidth,
39854 renderMode: Render_1.RenderMode.Fill,
39856 .filter(function (adaptive) {
39857 return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
39859 .map(function (adaptive) {
39860 var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
39861 var ratio = adaptive.imageAspect / elementAspect;
39862 var verticalOffset = 0;
39863 var horizontalOffset = 0;
39864 if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
39865 if (adaptive.imageAspect > elementAspect) {
39866 verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
39869 horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
39873 if (adaptive.imageAspect > elementAspect) {
39874 horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
39877 verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
39881 bottom: verticalOffset,
39882 left: horizontalOffset,
39883 right: horizontalOffset,
39884 top: verticalOffset,
39887 this._currentFrame$
39888 .filter(function (frame) {
39889 return frame.state.currentNode != null;
39891 .distinctUntilChanged(function (k1, k2) {
39893 }, function (frame) {
39894 return frame.state.currentNode.key;
39896 .map(function (frame) {
39897 return frame.state.currentTransform.basicAspect;
39899 .map(function (aspect) {
39900 return function (adaptive) {
39901 adaptive.imageAspect = aspect;
39905 .subscribe(this._adaptiveOperation$);
39906 this._renderAdaptive$
39907 .scan(function (vNodeHashes, vNodeHash) {
39908 if (vNodeHash.vnode == null) {
39909 delete vNodeHashes[vNodeHash.name];
39912 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
39914 return vNodeHashes;
39916 .combineLatest(this._offset$)
39917 .map(function (vo) {
39918 var vNodes = _.values(vo[0]);
39919 var offset = vo[1];
39922 bottom: offset.bottom + "px",
39923 left: offset.left + "px",
39924 "pointer-events": "none",
39925 position: "absolute",
39926 right: offset.right + "px",
39927 top: offset.top + "px",
39931 name: "adaptiveDomRenderer",
39932 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
39935 .subscribe(this._render$);
39936 this._vNode$ = this._render$
39937 .scan(function (vNodeHashes, vNodeHash) {
39938 if (vNodeHash.vnode == null) {
39939 delete vNodeHashes[vNodeHash.name];
39942 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
39944 return vNodeHashes;
39946 .map(function (vNodeHashes) {
39947 var vNodes = _.values(vNodeHashes);
39948 return vd.h("div.domRenderer", vNodes);
39950 this._vPatch$ = this._vNode$
39951 .scan(function (nodePatch, vNode) {
39952 nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
39953 nodePatch.vnode = vNode;
39955 }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
39957 this._element$ = this._vPatch$
39958 .scan(function (oldElement, vPatch) {
39959 return vd.patch(oldElement, vPatch);
39963 this._element$.subscribe(function () { });
39964 this._renderService.size$
39965 .map(function (size) {
39966 return function (adaptive) {
39967 adaptive.elementWidth = size.width;
39968 adaptive.elementHeight = size.height;
39972 .subscribe(this._adaptiveOperation$);
39973 this._renderService.renderMode$
39974 .map(function (renderMode) {
39975 return function (adaptive) {
39976 adaptive.renderMode = renderMode;
39980 .subscribe(this._adaptiveOperation$);
39982 Object.defineProperty(DOMRenderer.prototype, "element$", {
39984 return this._element$;
39989 Object.defineProperty(DOMRenderer.prototype, "render$", {
39991 return this._render$;
39996 Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
39998 return this._renderAdaptive$;
40003 DOMRenderer.prototype.clear = function (name) {
40004 this._renderAdaptive$.next({ name: name, vnode: null });
40005 this._render$.next({ name: name, vnode: null });
40007 return DOMRenderer;
40009 exports.DOMRenderer = DOMRenderer;
40010 exports.default = DOMRenderer;
40012 },{"../Render":287,"rxjs/Subject":34,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/pluck":70,"rxjs/add/operator/scan":75,"underscore":233,"virtual-dom":237}],398:[function(require,module,exports){
40014 Object.defineProperty(exports, "__esModule", { value: true });
40016 (function (GLRenderStage) {
40017 GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
40018 GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
40019 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
40020 exports.default = GLRenderStage;
40022 },{}],399:[function(require,module,exports){
40024 /// <reference path="../../typings/index.d.ts" />
40025 Object.defineProperty(exports, "__esModule", { value: true });
40026 var THREE = require("three");
40027 var Observable_1 = require("rxjs/Observable");
40028 var Subject_1 = require("rxjs/Subject");
40029 require("rxjs/add/observable/combineLatest");
40030 require("rxjs/add/operator/distinctUntilChanged");
40031 require("rxjs/add/operator/filter");
40032 require("rxjs/add/operator/first");
40033 require("rxjs/add/operator/map");
40034 require("rxjs/add/operator/merge");
40035 require("rxjs/add/operator/mergeMap");
40036 require("rxjs/add/operator/scan");
40037 require("rxjs/add/operator/share");
40038 require("rxjs/add/operator/startWith");
40039 var Render_1 = require("../Render");
40040 var Utils_1 = require("../Utils");
40041 var GLRenderer = /** @class */ (function () {
40042 function GLRenderer(canvasContainer, renderService, dom) {
40044 this._renderFrame$ = new Subject_1.Subject();
40045 this._renderCameraOperation$ = new Subject_1.Subject();
40046 this._render$ = new Subject_1.Subject();
40047 this._clear$ = new Subject_1.Subject();
40048 this._renderOperation$ = new Subject_1.Subject();
40049 this._rendererOperation$ = new Subject_1.Subject();
40050 this._eraserOperation$ = new Subject_1.Subject();
40051 this._renderService = renderService;
40052 this._dom = !!dom ? dom : new Utils_1.DOM();
40053 this._renderer$ = this._rendererOperation$
40054 .scan(function (renderer, operation) {
40055 return operation(renderer);
40056 }, { needsRender: false, renderer: null });
40057 this._renderCollection$ = this._renderOperation$
40058 .scan(function (hashes, operation) {
40059 return operation(hashes);
40062 this._renderCamera$ = this._renderCameraOperation$
40063 .scan(function (rc, operation) {
40064 return operation(rc);
40065 }, { frameId: -1, needsRender: false, perspective: null });
40066 this._eraser$ = this._eraserOperation$
40067 .startWith(function (eraser) {
40070 .scan(function (eraser, operation) {
40071 return operation(eraser);
40072 }, { needsRender: false });
40073 Observable_1.Observable
40074 .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
40075 var renders = Object.keys(hashes)
40076 .map(function (key) {
40077 return hashes[key];
40079 return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
40081 .filter(function (co) {
40082 var needsRender = co.renderer.needsRender ||
40083 co.camera.needsRender ||
40084 co.eraser.needsRender;
40085 var frameId = co.camera.frameId;
40086 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
40087 var render = _a[_i];
40088 if (render.frameId !== frameId) {
40091 needsRender = needsRender || render.needsRender;
40093 return needsRender;
40095 .distinctUntilChanged(function (n1, n2) {
40098 return co.eraser.needsRender ? -1 : co.camera.frameId;
40100 .subscribe(function (co) {
40101 co.renderer.needsRender = false;
40102 co.camera.needsRender = false;
40103 co.eraser.needsRender = false;
40104 var perspectiveCamera = co.camera.perspective;
40105 var backgroundRenders = [];
40106 var foregroundRenders = [];
40107 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
40108 var render = _a[_i];
40109 if (render.stage === Render_1.GLRenderStage.Background) {
40110 backgroundRenders.push(render.render);
40112 else if (render.stage === Render_1.GLRenderStage.Foreground) {
40113 foregroundRenders.push(render.render);
40116 var renderer = co.renderer.renderer;
40118 for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
40119 var render = backgroundRenders_1[_b];
40120 render(perspectiveCamera, renderer);
40122 renderer.clearDepth();
40123 for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
40124 var render = foregroundRenders_1[_c];
40125 render(perspectiveCamera, renderer);
40129 .map(function (rc) {
40130 return function (irc) {
40131 irc.frameId = rc.frameId;
40132 irc.perspective = rc.perspective;
40133 if (rc.changed === true) {
40134 irc.needsRender = true;
40139 .subscribe(this._renderCameraOperation$);
40140 this._renderFrameSubscribe();
40141 var renderHash$ = this._render$
40142 .map(function (hash) {
40143 return function (hashes) {
40144 hashes[hash.name] = hash.render;
40148 var clearHash$ = this._clear$
40149 .map(function (name) {
40150 return function (hashes) {
40151 delete hashes[name];
40155 Observable_1.Observable
40156 .merge(renderHash$, clearHash$)
40157 .subscribe(this._renderOperation$);
40158 this._webGLRenderer$ = this._render$
40160 .map(function (hash) {
40161 var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas");
40162 canvas.style.position = "absolute";
40163 canvas.setAttribute("tabindex", "0");
40164 canvasContainer.appendChild(canvas);
40165 var element = renderService.element;
40166 var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
40167 webGLRenderer.setPixelRatio(window.devicePixelRatio);
40168 webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
40169 webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
40170 webGLRenderer.autoClear = false;
40171 return webGLRenderer;
40175 this._webGLRenderer$.subscribe(function () { });
40176 var createRenderer$ = this._webGLRenderer$
40178 .map(function (webGLRenderer) {
40179 return function (renderer) {
40180 renderer.needsRender = true;
40181 renderer.renderer = webGLRenderer;
40185 var resizeRenderer$ = this._renderService.size$
40186 .map(function (size) {
40187 return function (renderer) {
40188 if (renderer.renderer == null) {
40191 renderer.renderer.setSize(size.width, size.height);
40192 renderer.needsRender = true;
40196 var clearRenderer$ = this._clear$
40197 .map(function (name) {
40198 return function (renderer) {
40199 if (renderer.renderer == null) {
40202 renderer.needsRender = true;
40206 Observable_1.Observable
40207 .merge(createRenderer$, resizeRenderer$, clearRenderer$)
40208 .subscribe(this._rendererOperation$);
40209 var renderCollectionEmpty$ = this._renderCollection$
40210 .filter(function (hashes) {
40211 return Object.keys(hashes).length === 0;
40214 renderCollectionEmpty$
40215 .subscribe(function (hashes) {
40216 if (_this._renderFrameSubscription == null) {
40219 _this._renderFrameSubscription.unsubscribe();
40220 _this._renderFrameSubscription = null;
40221 _this._renderFrameSubscribe();
40223 renderCollectionEmpty$
40224 .map(function (hashes) {
40225 return function (eraser) {
40226 eraser.needsRender = true;
40230 .subscribe(this._eraserOperation$);
40232 Object.defineProperty(GLRenderer.prototype, "render$", {
40234 return this._render$;
40239 Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
40241 return this._webGLRenderer$;
40246 GLRenderer.prototype.clear = function (name) {
40247 this._clear$.next(name);
40249 GLRenderer.prototype._renderFrameSubscribe = function () {
40253 .map(function (renderHash) {
40254 return function (irc) {
40255 irc.needsRender = true;
40259 .subscribe(function (operation) {
40260 _this._renderCameraOperation$.next(operation);
40262 this._renderFrameSubscription = this._render$
40264 .mergeMap(function (hash) {
40265 return _this._renderService.renderCameraFrame$;
40267 .subscribe(this._renderFrame$);
40271 exports.GLRenderer = GLRenderer;
40272 exports.default = GLRenderer;
40274 },{"../Render":287,"../Utils":291,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/scan":75,"rxjs/add/operator/share":76,"rxjs/add/operator/startWith":80,"three":231}],400:[function(require,module,exports){
40276 /// <reference path="../../typings/index.d.ts" />
40277 Object.defineProperty(exports, "__esModule", { value: true });
40278 var THREE = require("three");
40279 var Geo_1 = require("../Geo");
40280 var Render_1 = require("../Render");
40281 var RenderCamera = /** @class */ (function () {
40282 function RenderCamera(elementWidth, elementHeight, renderMode) {
40285 this._frameId = -1;
40286 this._changed = false;
40287 this._changedForFrame = -1;
40288 this.currentAspect = 1;
40289 this.currentPano = false;
40290 this.previousAspect = 1;
40291 this.previousPano = false;
40292 this.renderMode = renderMode;
40293 this._spatial = new Geo_1.Spatial();
40294 this._camera = new Geo_1.Camera();
40295 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
40296 this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
40297 this._perspective.matrixAutoUpdate = false;
40298 this._rotation = { phi: 0, theta: 0 };
40300 Object.defineProperty(RenderCamera.prototype, "camera", {
40302 return this._camera;
40307 Object.defineProperty(RenderCamera.prototype, "changed", {
40309 return this.frameId === this._changedForFrame;
40314 Object.defineProperty(RenderCamera.prototype, "frameId", {
40316 return this._frameId;
40318 set: function (value) {
40319 this._frameId = value;
40320 if (this._changed) {
40321 this._changed = false;
40322 this._changedForFrame = value;
40328 Object.defineProperty(RenderCamera.prototype, "perspective", {
40330 return this._perspective;
40335 Object.defineProperty(RenderCamera.prototype, "rotation", {
40337 return this._rotation;
40342 RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
40343 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
40344 this._perspective.aspect = perspectiveCameraAspect;
40345 this._changed = true;
40347 RenderCamera.prototype.updateProjection = function () {
40348 var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
40349 var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
40350 var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
40351 var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
40352 this._perspective.fov = verticalFov;
40353 this._perspective.updateProjectionMatrix();
40354 this._changed = true;
40356 RenderCamera.prototype.updatePerspective = function (camera) {
40357 this._perspective.up.copy(camera.up);
40358 this._perspective.position.copy(camera.position);
40359 this._perspective.lookAt(camera.lookat);
40360 this._perspective.updateMatrix();
40361 this._perspective.updateMatrixWorld(false);
40362 this._changed = true;
40364 RenderCamera.prototype.updateRotation = function (camera) {
40365 this._rotation = this._getRotation(camera);
40367 RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
40368 return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
40370 RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
40374 var coeff = Math.max(1, 1 / nodeAspect);
40375 var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
40376 nodeAspect > perspectiveCameraAspect :
40377 nodeAspect < perspectiveCameraAspect;
40378 var aspect = usePerspective ?
40379 coeff * perspectiveCameraAspect :
40380 coeff * nodeAspect;
40383 RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
40384 return elementWidth === 0 ? 0 : elementWidth / elementHeight;
40386 RenderCamera.prototype._getRotation = function (camera) {
40387 var direction = camera.lookat.clone().sub(camera.position);
40388 var up = camera.up.clone();
40389 var upProjection = direction.clone().dot(up);
40390 var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
40391 var phi = Math.atan2(planeProjection.y, planeProjection.x);
40392 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
40393 return { phi: phi, theta: theta };
40395 return RenderCamera;
40397 exports.RenderCamera = RenderCamera;
40398 exports.default = RenderCamera;
40400 },{"../Geo":284,"../Render":287,"three":231}],401:[function(require,module,exports){
40402 Object.defineProperty(exports, "__esModule", { value: true });
40404 * Enumeration for render mode
40407 * @description Modes for specifying how rendering is done
40408 * in the viewer. All modes preserves the original aspect
40409 * ratio of the images.
40412 (function (RenderMode) {
40414 * Displays all content within the viewer.
40416 * @description Black bars shown on both
40417 * sides of the content. Bars are shown
40418 * either below and above or to the left
40419 * and right of the content depending on
40420 * the aspect ratio relation between the
40421 * image and the viewer.
40423 RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
40425 * Fills the viewer by cropping content.
40427 * @description Cropping is done either
40428 * in horizontal or vertical direction
40429 * depending on the aspect ratio relation
40430 * between the image and the viewer.
40432 RenderMode[RenderMode["Fill"] = 1] = "Fill";
40433 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
40434 exports.default = RenderMode;
40436 },{}],402:[function(require,module,exports){
40438 /// <reference path="../../typings/index.d.ts" />
40439 Object.defineProperty(exports, "__esModule", { value: true });
40440 var Subject_1 = require("rxjs/Subject");
40441 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
40442 require("rxjs/add/observable/combineLatest");
40443 require("rxjs/add/operator/do");
40444 require("rxjs/add/operator/filter");
40445 require("rxjs/add/operator/map");
40446 require("rxjs/add/operator/publishReplay");
40447 require("rxjs/add/operator/scan");
40448 require("rxjs/add/operator/skip");
40449 require("rxjs/add/operator/startWith");
40450 require("rxjs/add/operator/withLatestFrom");
40451 var Geo_1 = require("../Geo");
40452 var Render_1 = require("../Render");
40453 var RenderService = /** @class */ (function () {
40454 function RenderService(element, currentFrame$, renderMode) {
40456 this._element = element;
40457 this._currentFrame$ = currentFrame$;
40458 this._spatial = new Geo_1.Spatial();
40459 renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
40460 this._resize$ = new Subject_1.Subject();
40461 this._renderCameraOperation$ = new Subject_1.Subject();
40463 new BehaviorSubject_1.BehaviorSubject({
40464 height: this._element.offsetHeight,
40465 width: this._element.offsetWidth,
40469 return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
40471 .subscribe(this._size$);
40472 this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
40473 this._renderCameraHolder$ = this._renderCameraOperation$
40474 .startWith(function (rc) {
40477 .scan(function (rc, operation) {
40478 return operation(rc);
40479 }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
40482 this._renderCameraFrame$ = this._currentFrame$
40483 .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
40484 return [frame, renderCamera];
40486 .do(function (args) {
40487 var frame = args[0];
40489 var camera = frame.state.camera;
40490 if (rc.alpha !== frame.state.alpha ||
40491 rc.zoom !== frame.state.zoom ||
40492 rc.camera.diff(camera) > 1e-9) {
40493 var currentTransform = frame.state.currentTransform;
40494 var previousTransform = frame.state.previousTransform != null ?
40495 frame.state.previousTransform :
40496 frame.state.currentTransform;
40497 var previousNode = frame.state.previousNode != null ?
40498 frame.state.previousNode :
40499 frame.state.currentNode;
40500 rc.currentAspect = currentTransform.basicAspect;
40501 rc.currentPano = frame.state.currentNode.pano;
40502 rc.previousAspect = previousTransform.basicAspect;
40503 rc.previousPano = previousNode.pano;
40504 rc.alpha = frame.state.alpha;
40505 rc.zoom = frame.state.zoom;
40506 rc.camera.copy(camera);
40507 rc.updatePerspective(camera);
40508 rc.updateRotation(camera);
40509 rc.updateProjection();
40511 rc.frameId = frame.id;
40513 .map(function (args) {
40518 this._renderCamera$ = this._renderCameraFrame$
40519 .filter(function (rc) {
40524 this._bearing$ = this._renderCamera$
40525 .map(function (renderCamera) {
40526 var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
40527 return _this._spatial.wrap(bearing, 0, 360);
40533 .map(function (size) {
40534 return function (rc) {
40535 rc.updateAspect(size.width, size.height);
40536 rc.updateProjection();
40540 .subscribe(this._renderCameraOperation$);
40543 .map(function (rm) {
40544 return function (rc) {
40545 rc.renderMode = rm;
40546 rc.updateProjection();
40550 .subscribe(this._renderCameraOperation$);
40551 this._bearing$.subscribe(function () { });
40552 this._renderCameraHolder$.subscribe(function () { });
40553 this._size$.subscribe(function () { });
40554 this._renderMode$.subscribe(function () { });
40555 this._renderCamera$.subscribe(function () { });
40556 this._renderCameraFrame$.subscribe(function () { });
40558 Object.defineProperty(RenderService.prototype, "bearing$", {
40560 return this._bearing$;
40565 Object.defineProperty(RenderService.prototype, "element", {
40567 return this._element;
40572 Object.defineProperty(RenderService.prototype, "resize$", {
40574 return this._resize$;
40579 Object.defineProperty(RenderService.prototype, "size$", {
40581 return this._size$;
40586 Object.defineProperty(RenderService.prototype, "renderMode$", {
40588 return this._renderMode$;
40593 Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
40595 return this._renderCameraFrame$;
40600 Object.defineProperty(RenderService.prototype, "renderCamera$", {
40602 return this._renderCamera$;
40607 return RenderService;
40609 exports.RenderService = RenderService;
40610 exports.default = RenderService;
40612 },{"../Geo":284,"../Render":287,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/skip":77,"rxjs/add/operator/startWith":80,"rxjs/add/operator/withLatestFrom":87}],403:[function(require,module,exports){
40614 Object.defineProperty(exports, "__esModule", { value: true });
40616 (function (State) {
40617 State[State["Traversing"] = 0] = "Traversing";
40618 State[State["Waiting"] = 1] = "Waiting";
40619 })(State = exports.State || (exports.State = {}));
40620 exports.default = State;
40622 },{}],404:[function(require,module,exports){
40624 Object.defineProperty(exports, "__esModule", { value: true });
40625 var State_1 = require("../State");
40626 var Geo_1 = require("../Geo");
40627 var StateContext = /** @class */ (function () {
40628 function StateContext() {
40629 this._state = new State_1.TraversingState({
40631 camera: new Geo_1.Camera(),
40633 reference: { alt: 0, lat: 0, lon: 0 },
40638 StateContext.prototype.traverse = function () {
40639 this._state = this._state.traverse();
40641 StateContext.prototype.wait = function () {
40642 this._state = this._state.wait();
40644 Object.defineProperty(StateContext.prototype, "state", {
40646 if (this._state instanceof State_1.TraversingState) {
40647 return State_1.State.Traversing;
40649 else if (this._state instanceof State_1.WaitingState) {
40650 return State_1.State.Waiting;
40652 throw new Error("Invalid state");
40657 Object.defineProperty(StateContext.prototype, "reference", {
40659 return this._state.reference;
40664 Object.defineProperty(StateContext.prototype, "alpha", {
40666 return this._state.alpha;
40671 Object.defineProperty(StateContext.prototype, "camera", {
40673 return this._state.camera;
40678 Object.defineProperty(StateContext.prototype, "zoom", {
40680 return this._state.zoom;
40685 Object.defineProperty(StateContext.prototype, "currentNode", {
40687 return this._state.currentNode;
40692 Object.defineProperty(StateContext.prototype, "previousNode", {
40694 return this._state.previousNode;
40699 Object.defineProperty(StateContext.prototype, "currentCamera", {
40701 return this._state.currentCamera;
40706 Object.defineProperty(StateContext.prototype, "currentTransform", {
40708 return this._state.currentTransform;
40713 Object.defineProperty(StateContext.prototype, "previousTransform", {
40715 return this._state.previousTransform;
40720 Object.defineProperty(StateContext.prototype, "trajectory", {
40722 return this._state.trajectory;
40727 Object.defineProperty(StateContext.prototype, "currentIndex", {
40729 return this._state.currentIndex;
40734 Object.defineProperty(StateContext.prototype, "lastNode", {
40736 return this._state.trajectory[this._state.trajectory.length - 1];
40741 Object.defineProperty(StateContext.prototype, "nodesAhead", {
40743 return this._state.trajectory.length - 1 - this._state.currentIndex;
40748 Object.defineProperty(StateContext.prototype, "motionless", {
40750 return this._state.motionless;
40755 StateContext.prototype.getCenter = function () {
40756 return this._state.getCenter();
40758 StateContext.prototype.setCenter = function (center) {
40759 this._state.setCenter(center);
40761 StateContext.prototype.setZoom = function (zoom) {
40762 this._state.setZoom(zoom);
40764 StateContext.prototype.update = function (fps) {
40765 this._state.update(fps);
40767 StateContext.prototype.append = function (nodes) {
40768 this._state.append(nodes);
40770 StateContext.prototype.prepend = function (nodes) {
40771 this._state.prepend(nodes);
40773 StateContext.prototype.remove = function (n) {
40774 this._state.remove(n);
40776 StateContext.prototype.clear = function () {
40777 this._state.clear();
40779 StateContext.prototype.clearPrior = function () {
40780 this._state.clearPrior();
40782 StateContext.prototype.cut = function () {
40785 StateContext.prototype.set = function (nodes) {
40786 this._state.set(nodes);
40788 StateContext.prototype.rotate = function (delta) {
40789 this._state.rotate(delta);
40791 StateContext.prototype.rotateBasic = function (basicRotation) {
40792 this._state.rotateBasic(basicRotation);
40794 StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
40795 this._state.rotateBasicUnbounded(basicRotation);
40797 StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) {
40798 this._state.rotateBasicWithoutInertia(basicRotation);
40800 StateContext.prototype.rotateToBasic = function (basic) {
40801 this._state.rotateToBasic(basic);
40803 StateContext.prototype.move = function (delta) {
40804 this._state.move(delta);
40806 StateContext.prototype.moveTo = function (delta) {
40807 this._state.moveTo(delta);
40809 StateContext.prototype.zoomIn = function (delta, reference) {
40810 this._state.zoomIn(delta, reference);
40812 StateContext.prototype.setSpeed = function (speed) {
40813 this._state.setSpeed(speed);
40815 return StateContext;
40817 exports.StateContext = StateContext;
40819 },{"../Geo":284,"../State":288}],405:[function(require,module,exports){
40821 Object.defineProperty(exports, "__esModule", { value: true });
40822 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
40823 var Subject_1 = require("rxjs/Subject");
40824 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
40825 require("rxjs/add/operator/bufferCount");
40826 require("rxjs/add/operator/distinctUntilChanged");
40827 require("rxjs/add/operator/do");
40828 require("rxjs/add/operator/filter");
40829 require("rxjs/add/operator/first");
40830 require("rxjs/add/operator/map");
40831 require("rxjs/add/operator/pairwise");
40832 require("rxjs/add/operator/publishReplay");
40833 require("rxjs/add/operator/scan");
40834 require("rxjs/add/operator/startWith");
40835 require("rxjs/add/operator/switchMap");
40836 require("rxjs/add/operator/withLatestFrom");
40837 var State_1 = require("../State");
40838 var StateService = /** @class */ (function () {
40839 function StateService() {
40841 this._appendNode$ = new Subject_1.Subject();
40842 this._start$ = new Subject_1.Subject();
40843 this._frame$ = new Subject_1.Subject();
40844 this._fpsSampleRate = 30;
40845 this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
40848 this._context$ = this._contextOperation$
40849 .scan(function (context, operation) {
40850 return operation(context);
40851 }, new State_1.StateContext())
40854 this._state$ = this._context$
40855 .map(function (context) {
40856 return context.state;
40858 .distinctUntilChanged()
40861 this._fps$ = this._start$
40862 .switchMap(function () {
40863 return _this._frame$
40864 .bufferCount(1, _this._fpsSampleRate)
40865 .map(function (frameIds) {
40866 return new Date().getTime();
40869 .map(function (times) {
40870 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
40875 this._currentState$ = this._frame$
40876 .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
40877 return [frameId, fps, context];
40879 .filter(function (fc) {
40880 return fc[2].currentNode != null;
40882 .do(function (fc) {
40883 fc[2].update(fc[1]);
40885 .map(function (fc) {
40886 return { fps: fc[1], id: fc[0], state: fc[2] };
40889 this._lastState$ = this._currentState$
40892 var nodeChanged$ = this._currentState$
40893 .distinctUntilChanged(undefined, function (f) {
40894 return f.state.currentNode.key;
40898 var nodeChangedSubject$ = new Subject_1.Subject();
40900 .subscribe(nodeChangedSubject$);
40901 this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
40902 nodeChangedSubject$
40903 .map(function (f) {
40904 return f.state.currentNode.key;
40906 .subscribe(this._currentKey$);
40907 this._currentNode$ = nodeChangedSubject$
40908 .map(function (f) {
40909 return f.state.currentNode;
40913 this._currentCamera$ = nodeChangedSubject$
40914 .map(function (f) {
40915 return f.state.currentCamera;
40919 this._currentTransform$ = nodeChangedSubject$
40920 .map(function (f) {
40921 return f.state.currentTransform;
40925 this._reference$ = nodeChangedSubject$
40926 .map(function (f) {
40927 return f.state.reference;
40929 .distinctUntilChanged(function (r1, r2) {
40930 return r1.lat === r2.lat && r1.lon === r2.lon;
40931 }, function (reference) {
40932 return { lat: reference.lat, lon: reference.lon };
40936 this._currentNodeExternal$ = nodeChanged$
40937 .map(function (f) {
40938 return f.state.currentNode;
40943 .map(function (node) {
40944 return function (context) {
40945 context.append([node]);
40949 .subscribe(this._contextOperation$);
40950 this._inMotionOperation$ = new Subject_1.Subject();
40952 .map(function (frame) {
40955 .subscribe(this._inMotionOperation$);
40956 this._inMotionOperation$
40957 .distinctUntilChanged()
40958 .filter(function (moving) {
40961 .switchMap(function (moving) {
40962 return _this._currentState$
40963 .filter(function (frame) {
40964 return frame.state.nodesAhead === 0;
40966 .map(function (frame) {
40967 return [frame.state.camera.clone(), frame.state.zoom];
40970 .map(function (pair) {
40971 var c1 = pair[0][0];
40972 var c2 = pair[1][0];
40973 var z1 = pair[0][1];
40974 var z2 = pair[1][1];
40975 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
40977 .first(function (changed) {
40981 .subscribe(this._inMotionOperation$);
40982 this._inMotion$ = this._inMotionOperation$
40983 .distinctUntilChanged()
40986 this._inTranslationOperation$ = new Subject_1.Subject();
40988 .map(function (frame) {
40991 .subscribe(this._inTranslationOperation$);
40992 this._inTranslationOperation$
40993 .distinctUntilChanged()
40994 .filter(function (inTranslation) {
40995 return inTranslation;
40997 .switchMap(function (inTranslation) {
40998 return _this._currentState$
40999 .filter(function (frame) {
41000 return frame.state.nodesAhead === 0;
41002 .map(function (frame) {
41003 return frame.state.camera.position.clone();
41006 .map(function (pair) {
41007 return pair[0].distanceToSquared(pair[1]) !== 0;
41009 .first(function (changed) {
41013 .subscribe(this._inTranslationOperation$);
41014 this._inTranslation$ = this._inTranslationOperation$
41015 .distinctUntilChanged()
41018 this._state$.subscribe(function () { });
41019 this._currentNode$.subscribe(function () { });
41020 this._currentCamera$.subscribe(function () { });
41021 this._currentTransform$.subscribe(function () { });
41022 this._reference$.subscribe(function () { });
41023 this._currentNodeExternal$.subscribe(function () { });
41024 this._lastState$.subscribe(function () { });
41025 this._inMotion$.subscribe(function () { });
41026 this._inTranslation$.subscribe(function () { });
41027 this._frameId = null;
41028 this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
41030 Object.defineProperty(StateService.prototype, "currentState$", {
41032 return this._currentState$;
41037 Object.defineProperty(StateService.prototype, "currentNode$", {
41039 return this._currentNode$;
41044 Object.defineProperty(StateService.prototype, "currentKey$", {
41046 return this._currentKey$;
41051 Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
41053 return this._currentNodeExternal$;
41058 Object.defineProperty(StateService.prototype, "currentCamera$", {
41060 return this._currentCamera$;
41065 Object.defineProperty(StateService.prototype, "currentTransform$", {
41067 return this._currentTransform$;
41072 Object.defineProperty(StateService.prototype, "state$", {
41074 return this._state$;
41079 Object.defineProperty(StateService.prototype, "reference$", {
41081 return this._reference$;
41086 Object.defineProperty(StateService.prototype, "inMotion$", {
41088 return this._inMotion$;
41093 Object.defineProperty(StateService.prototype, "inTranslation$", {
41095 return this._inTranslation$;
41100 Object.defineProperty(StateService.prototype, "appendNode$", {
41102 return this._appendNode$;
41107 StateService.prototype.traverse = function () {
41108 this._inMotionOperation$.next(true);
41109 this._invokeContextOperation(function (context) { context.traverse(); });
41111 StateService.prototype.wait = function () {
41112 this._invokeContextOperation(function (context) { context.wait(); });
41114 StateService.prototype.appendNodes = function (nodes) {
41115 this._invokeContextOperation(function (context) { context.append(nodes); });
41117 StateService.prototype.prependNodes = function (nodes) {
41118 this._invokeContextOperation(function (context) { context.prepend(nodes); });
41120 StateService.prototype.removeNodes = function (n) {
41121 this._invokeContextOperation(function (context) { context.remove(n); });
41123 StateService.prototype.clearNodes = function () {
41124 this._invokeContextOperation(function (context) { context.clear(); });
41126 StateService.prototype.clearPriorNodes = function () {
41127 this._invokeContextOperation(function (context) { context.clearPrior(); });
41129 StateService.prototype.cutNodes = function () {
41130 this._invokeContextOperation(function (context) { context.cut(); });
41132 StateService.prototype.setNodes = function (nodes) {
41133 this._invokeContextOperation(function (context) { context.set(nodes); });
41135 StateService.prototype.rotate = function (delta) {
41136 this._inMotionOperation$.next(true);
41137 this._invokeContextOperation(function (context) { context.rotate(delta); });
41139 StateService.prototype.rotateBasic = function (basicRotation) {
41140 this._inMotionOperation$.next(true);
41141 this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
41143 StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
41144 this._inMotionOperation$.next(true);
41145 this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
41147 StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) {
41148 this._inMotionOperation$.next(true);
41149 this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); });
41151 StateService.prototype.rotateToBasic = function (basic) {
41152 this._inMotionOperation$.next(true);
41153 this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
41155 StateService.prototype.move = function (delta) {
41156 this._inMotionOperation$.next(true);
41157 this._invokeContextOperation(function (context) { context.move(delta); });
41159 StateService.prototype.moveTo = function (position) {
41160 this._inMotionOperation$.next(true);
41161 this._invokeContextOperation(function (context) { context.moveTo(position); });
41164 * Change zoom level while keeping the reference point position approximately static.
41166 * @parameter {number} delta - Change in zoom level.
41167 * @parameter {Array<number>} reference - Reference point in basic coordinates.
41169 StateService.prototype.zoomIn = function (delta, reference) {
41170 this._inMotionOperation$.next(true);
41171 this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
41173 StateService.prototype.getCenter = function () {
41174 return this._lastState$
41176 .map(function (frame) {
41177 return frame.state.getCenter();
41180 StateService.prototype.getZoom = function () {
41181 return this._lastState$
41183 .map(function (frame) {
41184 return frame.state.zoom;
41187 StateService.prototype.setCenter = function (center) {
41188 this._inMotionOperation$.next(true);
41189 this._invokeContextOperation(function (context) { context.setCenter(center); });
41191 StateService.prototype.setSpeed = function (speed) {
41192 this._invokeContextOperation(function (context) { context.setSpeed(speed); });
41194 StateService.prototype.setZoom = function (zoom) {
41195 this._inMotionOperation$.next(true);
41196 this._invokeContextOperation(function (context) { context.setZoom(zoom); });
41198 StateService.prototype.start = function () {
41199 if (this._frameId == null) {
41200 this._start$.next(null);
41201 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
41202 this._frame$.next(this._frameId);
41205 StateService.prototype.stop = function () {
41206 if (this._frameId != null) {
41207 this._frameGenerator.cancelAnimationFrame(this._frameId);
41208 this._frameId = null;
41211 StateService.prototype._invokeContextOperation = function (action) {
41212 this._contextOperation$
41213 .next(function (context) {
41218 StateService.prototype._frame = function (time) {
41219 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
41220 this._frame$.next(this._frameId);
41222 return StateService;
41224 exports.StateService = StateService;
41226 },{"../State":288,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/pairwise":69,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/startWith":80,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/withLatestFrom":87,"rxjs/util/AnimationFrame":208}],406:[function(require,module,exports){
41228 /// <reference path="../../../typings/index.d.ts" />
41229 Object.defineProperty(exports, "__esModule", { value: true });
41230 var Error_1 = require("../../Error");
41231 var Geo_1 = require("../../Geo");
41232 var StateBase = /** @class */ (function () {
41233 function StateBase(state) {
41234 this._spatial = new Geo_1.Spatial();
41235 this._geoCoords = new Geo_1.GeoCoords();
41236 this._referenceThreshold = 0.01;
41237 this._reference = state.reference;
41238 this._alpha = state.alpha;
41239 this._camera = state.camera.clone();
41240 this._zoom = state.zoom;
41241 this._currentIndex = state.currentIndex;
41242 this._trajectory = state.trajectory.slice();
41243 this._trajectoryTransforms = [];
41244 this._trajectoryCameras = [];
41245 for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
41247 var translation = this._nodeToTranslation(node);
41248 var transform = new Geo_1.Transform(node, node.image, translation);
41249 this._trajectoryTransforms.push(transform);
41250 this._trajectoryCameras.push(new Geo_1.Camera(transform));
41252 this._currentNode = this._trajectory.length > 0 ?
41253 this._trajectory[this._currentIndex] :
41255 this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
41256 this._trajectory[this._currentIndex - 1] :
41258 this._currentCamera = this._trajectoryCameras.length > 0 ?
41259 this._trajectoryCameras[this._currentIndex].clone() :
41260 new Geo_1.Camera();
41261 this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
41262 this._trajectoryCameras[this._currentIndex - 1].clone() :
41263 this._currentCamera.clone();
41265 Object.defineProperty(StateBase.prototype, "reference", {
41267 return this._reference;
41272 Object.defineProperty(StateBase.prototype, "alpha", {
41274 return this._getAlpha();
41279 Object.defineProperty(StateBase.prototype, "camera", {
41281 return this._camera;
41286 Object.defineProperty(StateBase.prototype, "zoom", {
41293 Object.defineProperty(StateBase.prototype, "trajectory", {
41295 return this._trajectory;
41300 Object.defineProperty(StateBase.prototype, "currentIndex", {
41302 return this._currentIndex;
41307 Object.defineProperty(StateBase.prototype, "currentNode", {
41309 return this._currentNode;
41314 Object.defineProperty(StateBase.prototype, "previousNode", {
41316 return this._previousNode;
41321 Object.defineProperty(StateBase.prototype, "currentCamera", {
41323 return this._currentCamera;
41328 Object.defineProperty(StateBase.prototype, "currentTransform", {
41330 return this._trajectoryTransforms.length > 0 ?
41331 this._trajectoryTransforms[this.currentIndex] : null;
41336 Object.defineProperty(StateBase.prototype, "previousTransform", {
41338 return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
41339 this._trajectoryTransforms[this.currentIndex - 1] : null;
41344 Object.defineProperty(StateBase.prototype, "motionless", {
41346 return this._motionless;
41351 StateBase.prototype.append = function (nodes) {
41352 if (nodes.length < 1) {
41353 throw Error("Trajectory can not be empty");
41355 if (this._currentIndex < 0) {
41359 this._trajectory = this._trajectory.concat(nodes);
41360 this._appendToTrajectories(nodes);
41363 StateBase.prototype.prepend = function (nodes) {
41364 if (nodes.length < 1) {
41365 throw Error("Trajectory can not be empty");
41367 this._trajectory = nodes.slice().concat(this._trajectory);
41368 this._currentIndex += nodes.length;
41369 this._setCurrentNode();
41370 var referenceReset = this._setReference(this._currentNode);
41371 if (referenceReset) {
41372 this._setTrajectories();
41375 this._prependToTrajectories(nodes);
41377 this._setCurrentCamera();
41379 StateBase.prototype.remove = function (n) {
41381 throw Error("n must be a positive integer");
41383 if (this._currentIndex - 1 < n) {
41384 throw Error("Current and previous nodes can not be removed");
41386 for (var i = 0; i < n; i++) {
41387 this._trajectory.shift();
41388 this._trajectoryTransforms.shift();
41389 this._trajectoryCameras.shift();
41390 this._currentIndex--;
41392 this._setCurrentNode();
41394 StateBase.prototype.clearPrior = function () {
41395 if (this._currentIndex > 0) {
41396 this.remove(this._currentIndex - 1);
41399 StateBase.prototype.clear = function () {
41401 if (this._currentIndex > 0) {
41402 this.remove(this._currentIndex - 1);
41405 StateBase.prototype.cut = function () {
41406 while (this._trajectory.length - 1 > this._currentIndex) {
41407 this._trajectory.pop();
41408 this._trajectoryTransforms.pop();
41409 this._trajectoryCameras.pop();
41412 StateBase.prototype.set = function (nodes) {
41413 this._setTrajectory(nodes);
41414 this._setCurrentNode();
41415 this._setReference(this._currentNode);
41416 this._setTrajectories();
41417 this._setCurrentCamera();
41419 StateBase.prototype.getCenter = function () {
41420 return this._currentNode != null ?
41421 this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
41424 StateBase.prototype._setCurrent = function () {
41425 this._setCurrentNode();
41426 var referenceReset = this._setReference(this._currentNode);
41427 if (referenceReset) {
41428 this._setTrajectories();
41430 this._setCurrentCamera();
41432 StateBase.prototype._setCurrentCamera = function () {
41433 this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
41434 this._previousCamera = this._currentIndex > 0 ?
41435 this._trajectoryCameras[this._currentIndex - 1].clone() :
41436 this._currentCamera.clone();
41438 StateBase.prototype._motionlessTransition = function () {
41439 var nodesSet = this._currentNode != null && this._previousNode != null;
41440 return nodesSet && !(this._currentNode.merged &&
41441 this._previousNode.merged &&
41442 this._withinOriginalDistance() &&
41443 this._sameConnectedComponent());
41445 StateBase.prototype._setReference = function (node) {
41446 // do not reset reference if node is within threshold distance
41447 if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
41448 Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
41451 // do not reset reference if previous node exist and transition is with motion
41452 if (this._previousNode != null && !this._motionlessTransition()) {
41455 this._reference.lat = node.latLon.lat;
41456 this._reference.lon = node.latLon.lon;
41457 this._reference.alt = node.alt;
41460 StateBase.prototype._setCurrentNode = function () {
41461 this._currentNode = this._trajectory.length > 0 ?
41462 this._trajectory[this._currentIndex] :
41464 this._previousNode = this._currentIndex > 0 ?
41465 this._trajectory[this._currentIndex - 1] :
41468 StateBase.prototype._setTrajectory = function (nodes) {
41469 if (nodes.length < 1) {
41470 throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
41472 if (this._currentNode != null) {
41473 this._trajectory = [this._currentNode].concat(nodes);
41474 this._currentIndex = 1;
41477 this._trajectory = nodes.slice();
41478 this._currentIndex = 0;
41481 StateBase.prototype._setTrajectories = function () {
41482 this._trajectoryTransforms.length = 0;
41483 this._trajectoryCameras.length = 0;
41484 this._appendToTrajectories(this._trajectory);
41486 StateBase.prototype._appendToTrajectories = function (nodes) {
41487 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
41488 var node = nodes_1[_i];
41489 if (!node.assetsCached) {
41490 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
41492 var translation = this._nodeToTranslation(node);
41493 var transform = new Geo_1.Transform(node, node.image, translation);
41494 this._trajectoryTransforms.push(transform);
41495 this._trajectoryCameras.push(new Geo_1.Camera(transform));
41498 StateBase.prototype._prependToTrajectories = function (nodes) {
41499 for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
41501 if (!node.assetsCached) {
41502 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
41504 var translation = this._nodeToTranslation(node);
41505 var transform = new Geo_1.Transform(node, node.image, translation);
41506 this._trajectoryTransforms.unshift(transform);
41507 this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
41510 StateBase.prototype._nodeToTranslation = function (node) {
41511 var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
41512 var RC = this._spatial.rotate(C, node.rotation);
41513 return [-RC.x, -RC.y, -RC.z];
41515 StateBase.prototype._sameConnectedComponent = function () {
41516 var current = this._currentNode;
41517 var previous = this._previousNode;
41519 !current.mergeCC ||
41521 !previous.mergeCC) {
41524 return current.mergeCC === previous.mergeCC;
41526 StateBase.prototype._withinOriginalDistance = function () {
41527 var current = this._currentNode;
41528 var previous = this._previousNode;
41529 if (!current || !previous) {
41532 // 50 km/h moves 28m in 2s
41533 var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
41534 return distance < 25;
41538 exports.StateBase = StateBase;
41540 },{"../../Error":283,"../../Geo":284}],407:[function(require,module,exports){
41542 /// <reference path="../../../typings/index.d.ts" />
41543 var __extends = (this && this.__extends) || (function () {
41544 var extendStatics = Object.setPrototypeOf ||
41545 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41546 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41547 return function (d, b) {
41548 extendStatics(d, b);
41549 function __() { this.constructor = d; }
41550 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41553 Object.defineProperty(exports, "__esModule", { value: true });
41554 var THREE = require("three");
41555 var UnitBezier = require("@mapbox/unitbezier");
41556 var State_1 = require("../../State");
41557 var RotationDelta = /** @class */ (function () {
41558 function RotationDelta(phi, theta) {
41560 this._theta = theta;
41562 Object.defineProperty(RotationDelta.prototype, "phi", {
41566 set: function (value) {
41572 Object.defineProperty(RotationDelta.prototype, "theta", {
41574 return this._theta;
41576 set: function (value) {
41577 this._theta = value;
41582 Object.defineProperty(RotationDelta.prototype, "isZero", {
41584 return this._phi === 0 && this._theta === 0;
41589 RotationDelta.prototype.copy = function (delta) {
41590 this._phi = delta.phi;
41591 this._theta = delta.theta;
41593 RotationDelta.prototype.lerp = function (other, alpha) {
41594 this._phi = (1 - alpha) * this._phi + alpha * other.phi;
41595 this._theta = (1 - alpha) * this._theta + alpha * other.theta;
41597 RotationDelta.prototype.multiply = function (value) {
41598 this._phi *= value;
41599 this._theta *= value;
41601 RotationDelta.prototype.threshold = function (value) {
41602 this._phi = Math.abs(this._phi) > value ? this._phi : 0;
41603 this._theta = Math.abs(this._theta) > value ? this._theta : 0;
41605 RotationDelta.prototype.lengthSquared = function () {
41606 return this._phi * this._phi + this._theta * this._theta;
41608 RotationDelta.prototype.reset = function () {
41612 return RotationDelta;
41614 var TraversingState = /** @class */ (function (_super) {
41615 __extends(TraversingState, _super);
41616 function TraversingState(state) {
41617 var _this = _super.call(this, state) || this;
41618 _this._adjustCameras();
41619 _this._motionless = _this._motionlessTransition();
41620 _this._baseAlpha = _this._alpha;
41621 _this._animationSpeed = 1 / 40;
41622 _this._speedCoefficient = 1;
41623 _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
41624 _this._useBezier = false;
41625 _this._rotationDelta = new RotationDelta(0, 0);
41626 _this._requestedRotationDelta = null;
41627 _this._basicRotation = [0, 0];
41628 _this._requestedBasicRotation = null;
41629 _this._requestedBasicRotationUnbounded = null;
41630 _this._rotationAcceleration = 0.86;
41631 _this._rotationIncreaseAlpha = 0.97;
41632 _this._rotationDecreaseAlpha = 0.9;
41633 _this._rotationThreshold = 1e-3;
41634 _this._unboundedRotationAlpha = 0.8;
41635 _this._desiredZoom = state.zoom;
41636 _this._minZoom = 0;
41637 _this._maxZoom = 3;
41638 _this._lookatDepth = 10;
41639 _this._desiredLookat = null;
41640 _this._desiredCenter = null;
41643 TraversingState.prototype.traverse = function () {
41644 throw new Error("Not implemented");
41646 TraversingState.prototype.wait = function () {
41647 return new State_1.WaitingState(this);
41649 TraversingState.prototype.append = function (nodes) {
41650 var emptyTrajectory = this._trajectory.length === 0;
41651 if (emptyTrajectory) {
41652 this._resetTransition();
41654 _super.prototype.append.call(this, nodes);
41655 if (emptyTrajectory) {
41656 this._setDesiredCenter();
41657 this._setDesiredZoom();
41660 TraversingState.prototype.prepend = function (nodes) {
41661 var emptyTrajectory = this._trajectory.length === 0;
41662 if (emptyTrajectory) {
41663 this._resetTransition();
41665 _super.prototype.prepend.call(this, nodes);
41666 if (emptyTrajectory) {
41667 this._setDesiredCenter();
41668 this._setDesiredZoom();
41671 TraversingState.prototype.set = function (nodes) {
41672 _super.prototype.set.call(this, nodes);
41673 this._desiredLookat = null;
41674 this._resetTransition();
41675 this._clearRotation();
41676 this._setDesiredCenter();
41677 this._setDesiredZoom();
41678 if (this._trajectory.length < 3) {
41679 this._useBezier = true;
41682 TraversingState.prototype.move = function (delta) {
41683 throw new Error("Not implemented");
41685 TraversingState.prototype.moveTo = function (delta) {
41686 throw new Error("Not implemented");
41688 TraversingState.prototype.rotate = function (rotationDelta) {
41689 if (this._currentNode == null) {
41692 this._desiredZoom = this._zoom;
41693 this._desiredLookat = null;
41694 this._requestedBasicRotation = null;
41695 if (this._requestedRotationDelta != null) {
41696 this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
41697 this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
41700 this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
41703 TraversingState.prototype.rotateBasic = function (basicRotation) {
41704 if (this._currentNode == null) {
41707 this._desiredZoom = this._zoom;
41708 this._desiredLookat = null;
41709 this._requestedRotationDelta = null;
41710 if (this._requestedBasicRotation != null) {
41711 this._requestedBasicRotation[0] += basicRotation[0];
41712 this._requestedBasicRotation[1] += basicRotation[1];
41713 var threshold = 0.05 / Math.pow(2, this._zoom);
41714 this._requestedBasicRotation[0] =
41715 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
41716 this._requestedBasicRotation[1] =
41717 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
41720 this._requestedBasicRotation = basicRotation.slice();
41723 TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
41724 if (this._currentNode == null) {
41727 if (this._requestedBasicRotationUnbounded != null) {
41728 this._requestedBasicRotationUnbounded[0] += basicRotation[0];
41729 this._requestedBasicRotationUnbounded[1] += basicRotation[1];
41732 this._requestedBasicRotationUnbounded = basicRotation.slice();
41735 TraversingState.prototype.rotateBasicWithoutInertia = function (basic) {
41736 if (this._currentNode == null) {
41739 this._desiredZoom = this._zoom;
41740 this._desiredLookat = null;
41741 this._requestedRotationDelta = null;
41742 this._requestedBasicRotation = null;
41743 var threshold = 0.05 / Math.pow(2, this._zoom);
41744 var basicRotation = basic.slice();
41745 basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold);
41746 basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold);
41747 this._applyRotationBasic(basicRotation);
41749 TraversingState.prototype.rotateToBasic = function (basic) {
41750 if (this._currentNode == null) {
41753 this._desiredZoom = this._zoom;
41754 this._desiredLookat = null;
41755 basic[0] = this._spatial.clamp(basic[0], 0, 1);
41756 basic[1] = this._spatial.clamp(basic[1], 0, 1);
41757 var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
41758 this._currentCamera.lookat.fromArray(lookat);
41760 TraversingState.prototype.setSpeed = function (speed) {
41761 this._speedCoefficient = this._spatial.clamp(speed, 0, 10);
41763 TraversingState.prototype.zoomIn = function (delta, reference) {
41764 if (this._currentNode == null) {
41767 this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
41768 var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
41769 var currentCenterX = currentCenter[0];
41770 var currentCenterY = currentCenter[1];
41771 var zoom0 = Math.pow(2, this._zoom);
41772 var zoom1 = Math.pow(2, this._desiredZoom);
41773 var refX = reference[0];
41774 var refY = reference[1];
41775 if (this.currentTransform.gpano != null &&
41776 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
41777 if (refX - currentCenterX > 0.5) {
41780 else if (currentCenterX - refX > 0.5) {
41784 var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
41785 var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
41786 var gpano = this.currentTransform.gpano;
41787 if (this._currentNode.fullPano) {
41788 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
41789 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
41791 else if (gpano != null &&
41792 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
41793 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
41794 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
41797 newCenterX = this._spatial.clamp(newCenterX, 0, 1);
41798 newCenterY = this._spatial.clamp(newCenterY, 0, 1);
41800 this._desiredLookat = new THREE.Vector3()
41801 .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
41803 TraversingState.prototype.setCenter = function (center) {
41804 this._desiredLookat = null;
41805 this._requestedRotationDelta = null;
41806 this._requestedBasicRotation = null;
41807 this._desiredZoom = this._zoom;
41809 this._spatial.clamp(center[0], 0, 1),
41810 this._spatial.clamp(center[1], 0, 1),
41812 if (this._currentNode == null) {
41813 this._desiredCenter = clamped;
41816 this._desiredCenter = null;
41817 var currentLookat = new THREE.Vector3()
41818 .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
41819 var previousTransform = this.previousTransform != null ?
41820 this.previousTransform :
41821 this.currentTransform;
41822 var previousLookat = new THREE.Vector3()
41823 .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
41824 this._currentCamera.lookat.copy(currentLookat);
41825 this._previousCamera.lookat.copy(previousLookat);
41827 TraversingState.prototype.setZoom = function (zoom) {
41828 this._desiredLookat = null;
41829 this._requestedRotationDelta = null;
41830 this._requestedBasicRotation = null;
41831 this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
41832 this._desiredZoom = this._zoom;
41834 TraversingState.prototype.update = function (fps) {
41835 if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
41836 this._currentIndex += 1;
41837 this._useBezier = this._trajectory.length < 3 &&
41838 this._currentIndex + 1 === this._trajectory.length;
41839 this._setCurrent();
41840 this._resetTransition();
41841 this._clearRotation();
41842 this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
41843 this._desiredLookat = null;
41845 var animationSpeed = this._animationSpeed * (60 / fps);
41846 this._baseAlpha = Math.min(1, this._baseAlpha + this._speedCoefficient * animationSpeed);
41847 if (this._useBezier) {
41848 this._alpha = this._unitBezier.solve(this._baseAlpha);
41851 this._alpha = this._baseAlpha;
41853 this._updateRotation();
41854 if (!this._rotationDelta.isZero) {
41855 this._applyRotation(this._previousCamera);
41856 this._applyRotation(this._currentCamera);
41858 this._updateRotationBasic();
41859 if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
41860 this._applyRotationBasic(this._basicRotation);
41862 this._updateZoom(animationSpeed);
41863 this._updateLookat(animationSpeed);
41864 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
41866 TraversingState.prototype._getAlpha = function () {
41867 return this._motionless ? Math.ceil(this._alpha) : this._alpha;
41869 TraversingState.prototype._setCurrentCamera = function () {
41870 _super.prototype._setCurrentCamera.call(this);
41871 this._adjustCameras();
41873 TraversingState.prototype._adjustCameras = function () {
41874 if (this._previousNode == null) {
41877 var lookat = this._camera.lookat.clone().sub(this._camera.position);
41878 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
41879 if (this._currentNode.fullPano) {
41880 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
41883 TraversingState.prototype._resetTransition = function () {
41885 this._baseAlpha = 0;
41886 this._motionless = this._motionlessTransition();
41888 TraversingState.prototype._applyRotation = function (camera) {
41889 if (camera == null) {
41892 var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
41893 var qInverse = q.clone().inverse();
41894 var offset = new THREE.Vector3();
41895 offset.copy(camera.lookat).sub(camera.position);
41896 offset.applyQuaternion(q);
41897 var length = offset.length();
41898 var phi = Math.atan2(offset.y, offset.x);
41899 phi += this._rotationDelta.phi;
41900 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
41901 theta += this._rotationDelta.theta;
41902 theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
41903 offset.x = Math.sin(theta) * Math.cos(phi);
41904 offset.y = Math.sin(theta) * Math.sin(phi);
41905 offset.z = Math.cos(theta);
41906 offset.applyQuaternion(qInverse);
41907 camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
41909 TraversingState.prototype._applyRotationBasic = function (basicRotation) {
41910 var currentNode = this._currentNode;
41911 var previousNode = this._previousNode != null ?
41912 this.previousNode :
41914 var currentCamera = this._currentCamera;
41915 var previousCamera = this._previousCamera;
41916 var currentTransform = this.currentTransform;
41917 var previousTransform = this.previousTransform != null ?
41918 this.previousTransform :
41919 this.currentTransform;
41920 var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
41921 var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
41922 var currentGPano = currentTransform.gpano;
41923 var previousGPano = previousTransform.gpano;
41924 if (currentNode.fullPano) {
41925 currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
41926 currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95);
41928 else if (currentGPano != null &&
41929 currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
41930 currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
41931 currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
41934 currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1);
41935 currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
41937 if (previousNode.fullPano) {
41938 previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
41939 previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95);
41941 else if (previousGPano != null &&
41942 previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
41943 previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
41944 previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1);
41947 previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1);
41948 previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
41950 var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
41951 currentCamera.lookat.fromArray(currentLookat);
41952 var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
41953 previousCamera.lookat.fromArray(previousLookat);
41955 TraversingState.prototype._updateZoom = function (animationSpeed) {
41956 var diff = this._desiredZoom - this._zoom;
41957 var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
41961 else if (Math.abs(diff) < 2e-3) {
41962 this._zoom = this._desiredZoom;
41963 if (this._desiredLookat != null) {
41964 this._desiredLookat = null;
41968 this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
41971 TraversingState.prototype._updateLookat = function (animationSpeed) {
41972 if (this._desiredLookat === null) {
41975 var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
41976 if (Math.abs(diff) < 1e-6) {
41977 this._currentCamera.lookat.copy(this._desiredLookat);
41978 this._desiredLookat = null;
41981 this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
41984 TraversingState.prototype._updateRotation = function () {
41985 if (this._requestedRotationDelta != null) {
41986 var length_1 = this._rotationDelta.lengthSquared();
41987 var requestedLength = this._requestedRotationDelta.lengthSquared();
41988 if (requestedLength > length_1) {
41989 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
41992 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
41994 this._requestedRotationDelta = null;
41997 if (this._rotationDelta.isZero) {
42000 this._rotationDelta.multiply(this._rotationAcceleration);
42001 this._rotationDelta.threshold(this._rotationThreshold);
42003 TraversingState.prototype._updateRotationBasic = function () {
42004 if (this._requestedBasicRotation != null) {
42005 var x = this._basicRotation[0];
42006 var y = this._basicRotation[1];
42007 var reqX = this._requestedBasicRotation[0];
42008 var reqY = this._requestedBasicRotation[1];
42009 if (Math.abs(reqX) > Math.abs(x)) {
42010 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
42013 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
42015 if (Math.abs(reqY) > Math.abs(y)) {
42016 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
42019 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
42021 this._requestedBasicRotation = null;
42024 if (this._requestedBasicRotationUnbounded != null) {
42025 var reqX = this._requestedBasicRotationUnbounded[0];
42026 var reqY = this._requestedBasicRotationUnbounded[1];
42027 if (Math.abs(reqX) > 0) {
42028 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
42030 if (Math.abs(reqY) > 0) {
42031 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
42033 if (this._desiredLookat != null) {
42034 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
42035 desiredBasicLookat[0] += reqX;
42036 desiredBasicLookat[1] += reqY;
42037 this._desiredLookat = new THREE.Vector3()
42038 .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
42040 this._requestedBasicRotationUnbounded = null;
42042 if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
42045 this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
42046 this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
42047 if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
42048 Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
42049 this._basicRotation = [0, 0];
42052 TraversingState.prototype._clearRotation = function () {
42053 if (this._currentNode.fullPano) {
42056 if (this._requestedRotationDelta != null) {
42057 this._requestedRotationDelta = null;
42059 if (!this._rotationDelta.isZero) {
42060 this._rotationDelta.reset();
42062 if (this._requestedBasicRotation != null) {
42063 this._requestedBasicRotation = null;
42065 if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
42066 this._basicRotation = [0, 0];
42069 TraversingState.prototype._setDesiredCenter = function () {
42070 if (this._desiredCenter == null) {
42073 var lookatDirection = new THREE.Vector3()
42074 .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
42075 .sub(this._currentCamera.position);
42076 this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
42077 this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
42078 this._desiredCenter = null;
42080 TraversingState.prototype._setDesiredZoom = function () {
42081 this._desiredZoom =
42082 this._currentNode.fullPano || this._previousNode == null ?
42085 return TraversingState;
42086 }(State_1.StateBase));
42087 exports.TraversingState = TraversingState;
42089 },{"../../State":288,"@mapbox/unitbezier":2,"three":231}],408:[function(require,module,exports){
42091 var __extends = (this && this.__extends) || (function () {
42092 var extendStatics = Object.setPrototypeOf ||
42093 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42094 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42095 return function (d, b) {
42096 extendStatics(d, b);
42097 function __() { this.constructor = d; }
42098 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42101 Object.defineProperty(exports, "__esModule", { value: true });
42102 var State_1 = require("../../State");
42103 var WaitingState = /** @class */ (function (_super) {
42104 __extends(WaitingState, _super);
42105 function WaitingState(state) {
42106 var _this = _super.call(this, state) || this;
42108 _this._adjustCameras();
42109 _this._motionless = _this._motionlessTransition();
42112 WaitingState.prototype.traverse = function () {
42113 return new State_1.TraversingState(this);
42115 WaitingState.prototype.wait = function () {
42116 throw new Error("Not implemented");
42118 WaitingState.prototype.prepend = function (nodes) {
42119 _super.prototype.prepend.call(this, nodes);
42120 this._motionless = this._motionlessTransition();
42122 WaitingState.prototype.set = function (nodes) {
42123 _super.prototype.set.call(this, nodes);
42124 this._motionless = this._motionlessTransition();
42126 WaitingState.prototype.rotate = function (delta) { return; };
42127 WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
42128 WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
42129 WaitingState.prototype.rotateBasicWithoutInertia = function (basicRotation) { return; };
42130 WaitingState.prototype.rotateToBasic = function (basic) { return; };
42131 WaitingState.prototype.setSpeed = function (speed) { return; };
42132 WaitingState.prototype.zoomIn = function (delta, reference) { return; };
42133 WaitingState.prototype.move = function (delta) {
42134 this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
42136 WaitingState.prototype.moveTo = function (position) {
42137 this._alpha = Math.max(0, Math.min(1, position));
42139 WaitingState.prototype.update = function (fps) {
42140 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
42142 WaitingState.prototype.setCenter = function (center) { return; };
42143 WaitingState.prototype.setZoom = function (zoom) { return; };
42144 WaitingState.prototype._getAlpha = function () {
42145 return this._motionless ? Math.round(this._alpha) : this._alpha;
42147 WaitingState.prototype._setCurrentCamera = function () {
42148 _super.prototype._setCurrentCamera.call(this);
42149 this._adjustCameras();
42151 WaitingState.prototype._adjustCameras = function () {
42152 if (this._previousNode == null) {
42155 if (this._currentNode.fullPano) {
42156 var lookat = this._camera.lookat.clone().sub(this._camera.position);
42157 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
42159 if (this._previousNode.fullPano) {
42160 var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
42161 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
42164 return WaitingState;
42165 }(State_1.StateBase));
42166 exports.WaitingState = WaitingState;
42168 },{"../../State":288}],409:[function(require,module,exports){
42170 Object.defineProperty(exports, "__esModule", { value: true });
42171 var Observable_1 = require("rxjs/Observable");
42173 * @class ImageTileLoader
42175 * @classdesc Represents a loader of image tiles.
42177 var ImageTileLoader = /** @class */ (function () {
42179 * Create a new node image tile loader instance.
42181 * @param {string} scheme - The URI scheme.
42182 * @param {string} host - The URI host.
42183 * @param {string} [origin] - The origin query param.
42185 function ImageTileLoader(scheme, host, origin) {
42186 this._scheme = scheme;
42188 this._origin = origin != null ? "?origin=" + origin : "";
42191 * Retrieve an image tile.
42193 * @description Retrieve an image tile by specifying the area
42194 * as well as the scaled size.
42196 * @param {string} identifier - The identifier of the image.
42197 * @param {number} x - The top left x pixel coordinate for the tile
42198 * in the original image.
42199 * @param {number} y - The top left y pixel coordinate for the tile
42200 * in the original image.
42201 * @param {number} w - The pixel width of the tile in the original image.
42202 * @param {number} h - The pixel height of the tile in the original image.
42203 * @param {number} scaledW - The scaled width of the returned tile.
42204 * @param {number} scaledH - The scaled height of the returned tile.
42206 ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
42207 var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
42208 var url = this._scheme +
42213 var xmlHTTP = null;
42214 return [Observable_1.Observable.create(function (subscriber) {
42215 xmlHTTP = new XMLHttpRequest();
42216 xmlHTTP.open("GET", url, true);
42217 xmlHTTP.responseType = "arraybuffer";
42218 xmlHTTP.timeout = 15000;
42219 xmlHTTP.onload = function (event) {
42220 if (xmlHTTP.status !== 200) {
42221 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
42222 ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
42225 var image = new Image();
42226 image.crossOrigin = "Anonymous";
42227 image.onload = function (e) {
42228 subscriber.next(image);
42229 subscriber.complete();
42231 image.onerror = function (error) {
42232 subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
42234 var blob = new Blob([xmlHTTP.response]);
42235 image.src = window.URL.createObjectURL(blob);
42237 xmlHTTP.onerror = function (error) {
42238 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
42240 xmlHTTP.ontimeout = function (error) {
42241 subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
42243 xmlHTTP.onabort = function (event) {
42244 subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
42246 xmlHTTP.send(null);
42249 if (xmlHTTP != null) {
42255 return ImageTileLoader;
42257 exports.ImageTileLoader = ImageTileLoader;
42258 exports.default = ImageTileLoader;
42260 },{"rxjs/Observable":29}],410:[function(require,module,exports){
42262 Object.defineProperty(exports, "__esModule", { value: true });
42264 * @class ImageTileStore
42266 * @classdesc Represents a store for image tiles.
42268 var ImageTileStore = /** @class */ (function () {
42270 * Create a new node image tile store instance.
42272 function ImageTileStore() {
42276 * Add an image tile to the store.
42278 * @param {HTMLImageElement} image - The image tile.
42279 * @param {string} key - The identifier for the tile.
42280 * @param {number} level - The level of the tile.
42282 ImageTileStore.prototype.addImage = function (image, key, level) {
42283 if (!(level in this._images)) {
42284 this._images[level] = {};
42286 this._images[level][key] = image;
42289 * Dispose the store.
42291 * @description Disposes all cached assets.
42293 ImageTileStore.prototype.dispose = function () {
42294 for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
42295 var level = _a[_i];
42296 var levelImages = this._images[level];
42297 for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
42299 window.URL.revokeObjectURL(levelImages[key].src);
42300 delete levelImages[key];
42302 delete this._images[level];
42306 * Get an image tile from the store.
42308 * @param {string} key - The identifier for the tile.
42309 * @param {number} level - The level of the tile.
42311 ImageTileStore.prototype.getImage = function (key, level) {
42312 return this._images[level][key];
42315 * Check if an image tile exist in the store.
42317 * @param {string} key - The identifier for the tile.
42318 * @param {number} level - The level of the tile.
42320 ImageTileStore.prototype.hasImage = function (key, level) {
42321 return level in this._images && key in this._images[level];
42323 return ImageTileStore;
42325 exports.ImageTileStore = ImageTileStore;
42326 exports.default = ImageTileStore;
42328 },{}],411:[function(require,module,exports){
42330 /// <reference path="../../typings/index.d.ts" />
42331 Object.defineProperty(exports, "__esModule", { value: true });
42332 var Geo_1 = require("../Geo");
42334 * @class RegionOfInterestCalculator
42336 * @classdesc Represents a calculator for regions of interest.
42338 var RegionOfInterestCalculator = /** @class */ (function () {
42339 function RegionOfInterestCalculator() {
42340 this._viewportCoords = new Geo_1.ViewportCoords();
42343 * Compute a region of interest based on the current render camera
42344 * and the viewport size.
42346 * @param {RenderCamera} renderCamera - Render camera used for unprojections.
42347 * @param {ISize} size - Viewport size in pixels.
42348 * @param {Transform} transform - Transform used for projections.
42350 * @returns {IRegionOfInterest} A region of interest.
42352 RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
42353 var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
42354 var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
42355 this._clipBoundingBox(bbox);
42356 var viewportPixelWidth = 2 / size.width;
42357 var viewportPixelHeight = 2 / size.height;
42358 var centralViewportPixel = [
42359 [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
42360 [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
42361 [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
42362 [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
42364 var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
42367 pixelHeight: cpbox.maxY - cpbox.minY,
42368 pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
42371 RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
42373 var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
42374 var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
42375 for (var side = 0; side < 4; ++side) {
42378 for (var i = 0; i < pointsPerSide; ++i) {
42379 points.push([o[0] + d[0] * i / pointsPerSide,
42380 o[1] + d[1] * i / pointsPerSide]);
42385 RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
42387 var basicPoints = viewportPoints
42388 .map(function (point) {
42389 return _this._viewportCoords
42390 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
42392 if (transform.gpano != null) {
42393 return this._boundingBoxPano(basicPoints);
42396 return this._boundingBox(basicPoints);
42399 RegionOfInterestCalculator.prototype._boundingBox = function (points) {
42401 maxX: Number.NEGATIVE_INFINITY,
42402 maxY: Number.NEGATIVE_INFINITY,
42403 minX: Number.POSITIVE_INFINITY,
42404 minY: Number.POSITIVE_INFINITY,
42406 for (var i = 0; i < points.length; ++i) {
42407 bbox.minX = Math.min(bbox.minX, points[i][0]);
42408 bbox.maxX = Math.max(bbox.maxX, points[i][0]);
42409 bbox.minY = Math.min(bbox.minY, points[i][1]);
42410 bbox.maxY = Math.max(bbox.maxY, points[i][1]);
42414 RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
42418 for (var i = 0; i < points.length; ++i) {
42419 xs.push(points[i][0]);
42420 ys.push(points[i][1]);
42422 xs.sort(function (a, b) { return _this._sign(a - b); });
42423 ys.sort(function (a, b) { return _this._sign(a - b); });
42424 var intervalX = this._intervalPano(xs);
42426 maxX: intervalX[1],
42427 maxY: ys[ys.length - 1],
42428 minX: intervalX[0],
42433 * Find the max interval between consecutive numbers.
42434 * Assumes numbers are between 0 and 1, sorted and that
42435 * x is equivalent to x + 1.
42437 RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
42440 for (var i = 0; i < xs.length - 1; ++i) {
42441 var dx = xs[i + 1] - xs[i];
42447 var loopdx = xs[0] + 1 - xs[xs.length - 1];
42448 if (loopdx > maxdx) {
42449 return [xs[0], xs[xs.length - 1]];
42452 return [xs[maxi + 1], xs[maxi]];
42455 RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
42456 bbox.minX = Math.max(0, Math.min(1, bbox.minX));
42457 bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
42458 bbox.minY = Math.max(0, Math.min(1, bbox.minY));
42459 bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
42461 RegionOfInterestCalculator.prototype._sign = function (n) {
42462 return n > 0 ? 1 : n < 0 ? -1 : 0;
42464 return RegionOfInterestCalculator;
42466 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
42467 exports.default = RegionOfInterestCalculator;
42469 },{"../Geo":284}],412:[function(require,module,exports){
42471 /// <reference path="../../typings/index.d.ts" />
42472 Object.defineProperty(exports, "__esModule", { value: true });
42473 var THREE = require("three");
42474 var Subject_1 = require("rxjs/Subject");
42476 * @class TextureProvider
42478 * @classdesc Represents a provider of textures.
42480 var TextureProvider = /** @class */ (function () {
42482 * Create a new node texture provider instance.
42484 * @param {string} key - The identifier of the image for which to request tiles.
42485 * @param {number} width - The full width of the original image.
42486 * @param {number} height - The full height of the original image.
42487 * @param {number} tileSize - The size used when requesting tiles.
42488 * @param {HTMLImageElement} background - Image to use as background.
42489 * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
42490 * @param {ImageTileStore} imageTileStore - Store for saving tiles.
42491 * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
42493 function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
42494 this._disposed = false;
42496 if (width <= 0 || height <= 0) {
42497 console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
42499 this._width = width;
42500 this._height = height;
42501 this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
42502 this._currentLevel = -1;
42503 this._tileSize = tileSize;
42504 this._updated$ = new Subject_1.Subject();
42505 this._createdSubject$ = new Subject_1.Subject();
42506 this._created$ = this._createdSubject$
42509 this._createdSubscription = this._created$.subscribe(function () { });
42510 this._hasSubject$ = new Subject_1.Subject();
42511 this._has$ = this._hasSubject$
42515 this._hasSubscription = this._has$.subscribe(function () { });
42516 this._abortFunctions = [];
42517 this._tileSubscriptions = {};
42518 this._renderedCurrentLevelTiles = {};
42519 this._renderedTiles = {};
42520 this._background = background;
42521 this._camera = null;
42522 this._imageTileLoader = imageTileLoader;
42523 this._imageTileStore = imageTileStore;
42524 this._renderer = renderer;
42525 this._renderTarget = null;
42528 Object.defineProperty(TextureProvider.prototype, "disposed", {
42532 * @returns {boolean} Value indicating whether provider has
42536 return this._disposed;
42541 Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
42545 * @returns {Observable<boolean>} Observable emitting
42546 * values indicating when the existance of a texture
42555 Object.defineProperty(TextureProvider.prototype, "key", {
42559 * @returns {boolean} The identifier of the image for
42560 * which to render textures.
42568 Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
42570 * Get textureUpdated$.
42572 * @returns {Observable<boolean>} Observable emitting
42573 * values when an existing texture has been updated.
42576 return this._updated$;
42581 Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
42583 * Get textureCreated$.
42585 * @returns {Observable<boolean>} Observable emitting
42586 * values when a new texture has been created.
42589 return this._created$;
42595 * Abort all outstanding image tile requests.
42597 TextureProvider.prototype.abort = function () {
42598 for (var key in this._tileSubscriptions) {
42599 if (!this._tileSubscriptions.hasOwnProperty(key)) {
42602 this._tileSubscriptions[key].unsubscribe();
42604 this._tileSubscriptions = {};
42605 for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
42606 var abort = _a[_i];
42609 this._abortFunctions = [];
42612 * Dispose the provider.
42614 * @description Disposes all cached assets and
42615 * aborts all outstanding image tile requests.
42617 TextureProvider.prototype.dispose = function () {
42618 if (this._disposed) {
42619 console.warn("Texture already disposed (" + this._key + ")");
42623 if (this._renderTarget != null) {
42624 this._renderTarget.dispose();
42625 this._renderTarget = null;
42627 this._imageTileStore.dispose();
42628 this._imageTileStore = null;
42629 this._background = null;
42630 this._camera = null;
42631 this._imageTileLoader = null;
42632 this._renderer = null;
42634 this._createdSubscription.unsubscribe();
42635 this._hasSubscription.unsubscribe();
42636 this._disposed = true;
42639 * Set the region of interest.
42641 * @description When the region of interest is set the
42642 * the tile level is determined and tiles for the region
42643 * are fetched from the store or the loader and renderedLevel
42646 * @param {IRegionOfInterest} roi - Spatial edges to cache.
42648 TextureProvider.prototype.setRegionOfInterest = function (roi) {
42649 if (this._width <= 0 || this._height <= 0) {
42653 var width = 1 / this._roi.pixelWidth;
42654 var height = 1 / this._roi.pixelHeight;
42655 var size = Math.max(height, width);
42656 var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2))));
42657 if (currentLevel !== this._currentLevel) {
42659 this._currentLevel = currentLevel;
42660 if (!(this._currentLevel in this._renderedTiles)) {
42661 this._renderedTiles[this._currentLevel] = [];
42663 this._renderedCurrentLevelTiles = {};
42664 for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
42666 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
42669 var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
42670 var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
42671 var tiles = this._getTiles(topLeft, bottomRight);
42672 if (this._camera == null) {
42673 this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
42674 this._camera.position.z = 1;
42675 var gl = this._renderer.getContext();
42676 var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
42677 var backgroundSize = Math.max(this._width, this._height);
42678 var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
42679 var targetWidth = Math.floor(scale * this._width);
42680 var targetHeight = Math.floor(scale * this._height);
42681 this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
42682 depthBuffer: false,
42683 format: THREE.RGBFormat,
42684 magFilter: THREE.LinearFilter,
42685 minFilter: THREE.LinearFilter,
42686 stencilBuffer: false,
42688 this._renderToTarget(0, 0, this._width, this._height, this._background);
42689 this._createdSubject$.next(this._renderTarget.texture);
42690 this._hasSubject$.next(true);
42692 this._fetchTiles(tiles);
42694 TextureProvider.prototype.setTileSize = function (tileSize) {
42695 this._tileSize = tileSize;
42698 * Update the image used as background for the texture.
42700 * @param {HTMLImageElement} background - The background image.
42702 TextureProvider.prototype.updateBackground = function (background) {
42703 this._background = background;
42706 * Retrieve an image tile.
42708 * @description Retrieve an image tile and render it to the
42709 * texture. Add the tile to the store and emit to the updated
42712 * @param {Array<number>} tile - The tile coordinates.
42713 * @param {number} level - The tile level.
42714 * @param {number} x - The top left x pixel coordinate of the tile.
42715 * @param {number} y - The top left y pixel coordinate of the tile.
42716 * @param {number} w - The pixel width of the tile.
42717 * @param {number} h - The pixel height of the tile.
42718 * @param {number} scaledW - The scaled width of the returned tile.
42719 * @param {number} scaledH - The scaled height of the returned tile.
42721 TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
42723 var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
42724 var tile$ = getTile[0];
42725 var abort = getTile[1];
42726 this._abortFunctions.push(abort);
42727 var tileKey = this._tileKey(this._tileSize, tile);
42728 var subscription = tile$
42729 .subscribe(function (image) {
42730 _this._renderToTarget(x, y, w, h, image);
42731 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
42732 _this._removeFromArray(abort, _this._abortFunctions);
42733 _this._setTileRendered(tile, _this._currentLevel);
42734 _this._imageTileStore.addImage(image, tileKey, level);
42735 _this._updated$.next(true);
42736 }, function (error) {
42737 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
42738 _this._removeFromArray(abort, _this._abortFunctions);
42739 console.error(error);
42741 if (!subscription.closed) {
42742 this._tileSubscriptions[tileKey] = subscription;
42746 * Retrieve image tiles.
42748 * @description Retrieve a image tiles and render them to the
42749 * texture. Retrieve from store if it exists, otherwise Retrieve
42752 * @param {Array<Array<number>>} tiles - Array of tile coordinates to
42755 TextureProvider.prototype._fetchTiles = function (tiles) {
42756 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
42757 for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
42758 var tile = tiles_1[_i];
42759 var tileKey = this._tileKey(this._tileSize, tile);
42760 if (tileKey in this._renderedCurrentLevelTiles ||
42761 tileKey in this._tileSubscriptions) {
42764 var tileX = tileSize * tile[0];
42765 var tileY = tileSize * tile[1];
42766 var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
42767 var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
42768 if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
42769 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
42770 this._setTileRendered(tile, this._currentLevel);
42771 this._updated$.next(true);
42774 var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
42775 var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
42776 this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
42780 * Get tile coordinates for a point using the current level.
42782 * @param {Array<number>} point - Point in basic coordinates.
42784 * @returns {Array<number>} x and y tile coodinates.
42786 TextureProvider.prototype._getTileCoords = function (point) {
42787 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
42788 var maxX = Math.ceil(this._width / tileSize) - 1;
42789 var maxY = Math.ceil(this._height / tileSize) - 1;
42791 Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
42792 Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
42796 * Get tile coordinates for all tiles contained in a bounding
42799 * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
42800 * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
42802 * @returns {Array<Array<number>>} Array of x, y tile coodinates.
42804 TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
42806 if (topLeft[0] > bottomRight[0]) {
42807 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
42808 var maxX = Math.ceil(this._width / tileSize) - 1;
42809 for (var x = topLeft[0]; x <= maxX; x++) {
42812 for (var x = 0; x <= bottomRight[0]; x++) {
42817 for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
42822 for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
42824 for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
42825 tiles.push([x, y]);
42831 * Remove an item from an array if it exists in array.
42833 * @param {T} item - Item to remove.
42834 * @param {Array<T>} array - Array from which item should be removed.
42836 TextureProvider.prototype._removeFromArray = function (item, array) {
42837 var index = array.indexOf(item);
42838 if (index !== -1) {
42839 array.splice(index, 1);
42843 * Remove an item from a dictionary.
42845 * @param {string} key - Key of the item to remove.
42846 * @param {Object} dict - Dictionary from which item should be removed.
42848 TextureProvider.prototype._removeFromDictionary = function (key, dict) {
42854 * Render an image tile to the target texture.
42856 * @param {number} x - The top left x pixel coordinate of the tile.
42857 * @param {number} y - The top left y pixel coordinate of the tile.
42858 * @param {number} w - The pixel width of the tile.
42859 * @param {number} h - The pixel height of the tile.
42860 * @param {HTMLImageElement} background - The image tile to render.
42862 TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
42863 var texture = new THREE.Texture(image);
42864 texture.minFilter = THREE.LinearFilter;
42865 texture.needsUpdate = true;
42866 var geometry = new THREE.PlaneGeometry(w, h);
42867 var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
42868 var mesh = new THREE.Mesh(geometry, material);
42869 mesh.position.x = -this._width / 2 + x + w / 2;
42870 mesh.position.y = this._height / 2 - y - h / 2;
42871 var scene = new THREE.Scene();
42873 this._renderer.render(scene, this._camera, this._renderTarget);
42874 this._renderer.setRenderTarget(undefined);
42875 scene.remove(mesh);
42876 geometry.dispose();
42877 material.dispose();
42881 * Mark a tile as rendered.
42883 * @description Clears tiles marked as rendered in other
42884 * levels of the tile pyramid if they were rendered on
42885 * top of or below the tile.
42887 * @param {Arrary<number>} tile - The tile coordinates.
42888 * @param {number} level - Tile level of the tile coordinates.
42890 TextureProvider.prototype._setTileRendered = function (tile, level) {
42891 var otherLevels = Object.keys(this._renderedTiles)
42892 .map(function (key) {
42893 return parseInt(key, 10);
42895 .filter(function (renderedLevel) {
42896 return renderedLevel !== level;
42898 for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
42899 var otherLevel = otherLevels_1[_i];
42900 var scale = Math.pow(2, otherLevel - level);
42901 if (otherLevel < level) {
42902 var x = Math.floor(scale * tile[0]);
42903 var y = Math.floor(scale * tile[1]);
42904 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
42905 var otherTile = _b[_a];
42906 if (otherTile[0] === x && otherTile[1] === y) {
42907 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
42908 this._renderedTiles[otherLevel].splice(index, 1);
42913 var startX = scale * tile[0];
42914 var endX = startX + scale - 1;
42915 var startY = scale * tile[1];
42916 var endY = startY + scale - 1;
42917 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
42918 var otherTile = _d[_c];
42919 if (otherTile[0] >= startX && otherTile[0] <= endX &&
42920 otherTile[1] >= startY && otherTile[1] <= endY) {
42921 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
42922 this._renderedTiles[otherLevel].splice(index, 1);
42926 if (this._renderedTiles[otherLevel].length === 0) {
42927 delete this._renderedTiles[otherLevel];
42930 this._renderedTiles[level].push(tile);
42931 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
42934 * Create a tile key from a tile coordinates.
42936 * @description Tile keys are used as a hash for
42937 * storing the tile in a dictionary.
42939 * @param {number} tileSize - The tile size.
42940 * @param {Arrary<number>} tile - The tile coordinates.
42942 TextureProvider.prototype._tileKey = function (tileSize, tile) {
42943 return tileSize + "-" + tile[0] + "-" + tile[1];
42945 return TextureProvider;
42947 exports.TextureProvider = TextureProvider;
42948 exports.default = TextureProvider;
42950 },{"rxjs/Subject":34,"three":231}],413:[function(require,module,exports){
42952 Object.defineProperty(exports, "__esModule", { value: true });
42953 var DOM = /** @class */ (function () {
42954 function DOM(doc) {
42955 this._document = !!doc ? doc : document;
42957 Object.defineProperty(DOM.prototype, "document", {
42959 return this._document;
42964 DOM.prototype.createElement = function (tagName, className, container) {
42965 var element = this._document.createElement(tagName);
42967 element.className = className;
42970 container.appendChild(element);
42977 exports.default = DOM;
42979 },{}],414:[function(require,module,exports){
42981 Object.defineProperty(exports, "__esModule", { value: true });
42982 var EventEmitter = /** @class */ (function () {
42983 function EventEmitter() {
42987 * Subscribe to an event by its name.
42988 * @param {string }eventType - The name of the event to subscribe to.
42989 * @param {any} fn - The handler called when the event occurs.
42991 EventEmitter.prototype.on = function (eventType, fn) {
42992 this._events[eventType] = this._events[eventType] || [];
42993 this._events[eventType].push(fn);
42997 * Unsubscribe from an event by its name.
42998 * @param {string} eventType - The name of the event to subscribe to.
42999 * @param {any} fn - The handler to remove.
43001 EventEmitter.prototype.off = function (eventType, fn) {
43006 if (!this._listens(eventType)) {
43007 var idx = this._events[eventType].indexOf(fn);
43009 this._events[eventType].splice(idx, 1);
43011 if (this._events[eventType].length) {
43012 delete this._events[eventType];
43016 delete this._events[eventType];
43020 EventEmitter.prototype.fire = function (eventType, data) {
43021 if (!this._listens(eventType)) {
43024 for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
43026 fn.call(this, data);
43030 EventEmitter.prototype._listens = function (eventType) {
43031 return !!(this._events && this._events[eventType]);
43033 return EventEmitter;
43035 exports.EventEmitter = EventEmitter;
43036 exports.default = EventEmitter;
43038 },{}],415:[function(require,module,exports){
43040 Object.defineProperty(exports, "__esModule", { value: true });
43041 var Viewer_1 = require("../Viewer");
43042 var Settings = /** @class */ (function () {
43043 function Settings() {
43045 Settings.setOptions = function (options) {
43046 Settings._baseImageSize = options.baseImageSize != null ?
43047 options.baseImageSize :
43048 Viewer_1.ImageSize.Size640;
43049 Settings._basePanoramaSize = options.basePanoramaSize != null ?
43050 options.basePanoramaSize :
43051 Viewer_1.ImageSize.Size2048;
43052 Settings._maxImageSize = options.maxImageSize != null ?
43053 options.maxImageSize :
43054 Viewer_1.ImageSize.Size2048;
43056 Object.defineProperty(Settings, "baseImageSize", {
43058 return Settings._baseImageSize;
43063 Object.defineProperty(Settings, "basePanoramaSize", {
43065 return Settings._basePanoramaSize;
43070 Object.defineProperty(Settings, "maxImageSize", {
43072 return Settings._maxImageSize;
43079 exports.Settings = Settings;
43080 exports.default = Settings;
43082 },{"../Viewer":292}],416:[function(require,module,exports){
43084 Object.defineProperty(exports, "__esModule", { value: true });
43085 function isBrowser() {
43086 return typeof window !== "undefined" && typeof document !== "undefined";
43088 exports.isBrowser = isBrowser;
43089 function isArraySupported() {
43090 return !!(Array.prototype &&
43091 Array.prototype.filter &&
43092 Array.prototype.indexOf &&
43093 Array.prototype.map &&
43094 Array.prototype.reverse);
43096 exports.isArraySupported = isArraySupported;
43097 function isFunctionSupported() {
43098 return !!(Function.prototype && Function.prototype.bind);
43100 exports.isFunctionSupported = isFunctionSupported;
43101 function isJSONSupported() {
43102 return "JSON" in window && "parse" in JSON && "stringify" in JSON;
43104 exports.isJSONSupported = isJSONSupported;
43105 function isObjectSupported() {
43106 return !!(Object.keys &&
43109 exports.isObjectSupported = isObjectSupported;
43110 var isWebGLSupportedCache = undefined;
43111 function isWebGLSupportedCached() {
43112 if (isWebGLSupportedCache === undefined) {
43113 isWebGLSupportedCache = isWebGLSupported();
43115 return isWebGLSupportedCache;
43117 exports.isWebGLSupportedCached = isWebGLSupportedCached;
43118 function isWebGLSupported() {
43119 var webGLContextAttributes = {
43123 failIfMajorPerformanceCaveat: false,
43124 premultipliedAlpha: true,
43125 preserveDrawingBuffer: false,
43128 var canvas = document.createElement("canvas");
43129 var context = canvas.getContext("webgl", webGLContextAttributes) ||
43130 canvas.getContext("experimental-webgl", webGLContextAttributes);
43134 var requiredExtensions = [
43135 "OES_standard_derivatives",
43137 var supportedExtensions = context.getSupportedExtensions();
43138 for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
43139 var requiredExtension = requiredExtensions_1[_i];
43140 if (supportedExtensions.indexOf(requiredExtension) === -1) {
43146 exports.isWebGLSupported = isWebGLSupported;
43148 },{}],417:[function(require,module,exports){
43150 Object.defineProperty(exports, "__esModule", { value: true });
43151 var Urls = /** @class */ (function () {
43154 Object.defineProperty(Urls, "tileScheme", {
43161 Object.defineProperty(Urls, "tileDomain", {
43163 return "d2qb1440i7l50o.cloudfront.net";
43168 Object.defineProperty(Urls, "origin", {
43170 return "mapillary.webgl";
43175 Urls.thumbnail = function (key, size) {
43176 return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
43178 Urls.falcorModel = function (clientId) {
43179 return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
43181 Urls.protoMesh = function (key) {
43182 return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
43186 exports.Urls = Urls;
43187 exports.default = Urls;
43189 },{}],418:[function(require,module,exports){
43191 Object.defineProperty(exports, "__esModule", { value: true });
43193 * Enumeration for alignments
43198 (function (Alignment) {
43202 Alignment[Alignment["Bottom"] = 0] = "Bottom";
43204 * Align to bottom left
43206 Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
43208 * Align to bottom right
43210 Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
43214 Alignment[Alignment["Center"] = 3] = "Center";
43218 Alignment[Alignment["Left"] = 4] = "Left";
43222 Alignment[Alignment["Right"] = 5] = "Right";
43226 Alignment[Alignment["Top"] = 6] = "Top";
43228 * Align to top left
43230 Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
43232 * Align to top right
43234 Alignment[Alignment["TopRight"] = 8] = "TopRight";
43235 })(Alignment = exports.Alignment || (exports.Alignment = {}));
43236 exports.default = Alignment;
43238 },{}],419:[function(require,module,exports){
43240 Object.defineProperty(exports, "__esModule", { value: true });
43241 var Observable_1 = require("rxjs/Observable");
43242 require("rxjs/add/operator/bufferCount");
43243 require("rxjs/add/operator/delay");
43244 require("rxjs/add/operator/distinctUntilChanged");
43245 require("rxjs/add/operator/map");
43246 require("rxjs/add/operator/switchMap");
43247 require("rxjs/add/operator/timeout");
43248 var Graph_1 = require("../Graph");
43249 var CacheService = /** @class */ (function () {
43250 function CacheService(graphService, stateService) {
43251 this._graphService = graphService;
43252 this._stateService = stateService;
43253 this._started = false;
43255 Object.defineProperty(CacheService.prototype, "started", {
43257 return this._started;
43262 CacheService.prototype.start = function () {
43264 if (this._started) {
43267 this._uncacheSubscription = this._stateService.currentState$
43268 .distinctUntilChanged(undefined, function (frame) {
43269 return frame.state.currentNode.key;
43271 .map(function (frame) {
43272 var trajectory = frame.state.trajectory;
43273 var trajectoryKeys = trajectory
43274 .map(function (n) {
43277 var sequenceKey = trajectory[trajectory.length - 1].sequenceKey;
43278 return [trajectoryKeys, sequenceKey];
43281 .withLatestFrom(this._graphService.graphMode$)
43282 .switchMap(function (_a) {
43283 var keepBuffer = _a[0], graphMode = _a[1];
43284 var keepKeys = keepBuffer[0][0];
43285 var keepSequenceKey = graphMode === Graph_1.GraphMode.Sequence ?
43286 keepBuffer[0][1] : undefined;
43287 return _this._graphService.uncache$(keepKeys, keepSequenceKey);
43289 .subscribe(function () { });
43290 this._cacheNodeSubscription = this._graphService.graphMode$
43292 .withLatestFrom(this._stateService.currentState$)
43293 .switchMap(function (_a) {
43294 var mode = _a[0], frame = _a[1];
43295 return mode === Graph_1.GraphMode.Sequence ?
43296 _this._keyToEdges(frame.state.currentNode.key, function (node) {
43297 return node.sequenceEdges$;
43299 Observable_1.Observable
43300 .from(frame.state.trajectory
43301 .map(function (node) {
43304 .slice(frame.state.currentIndex))
43305 .mergeMap(function (key) {
43306 return _this._keyToEdges(key, function (node) {
43307 return node.spatialEdges$;
43311 .subscribe(function () { });
43312 this._started = true;
43314 CacheService.prototype.stop = function () {
43315 if (!this._started) {
43318 this._uncacheSubscription.unsubscribe();
43319 this._uncacheSubscription = null;
43320 this._cacheNodeSubscription.unsubscribe();
43321 this._cacheNodeSubscription = null;
43322 this._started = false;
43324 CacheService.prototype._keyToEdges = function (key, nodeToEdgeMap) {
43325 return this._graphService.cacheNode$(key)
43326 .switchMap(nodeToEdgeMap)
43327 .first(function (status) {
43328 return status.cached;
43331 .catch(function (error) {
43332 console.error("Failed to cache edges (" + key + ").", error);
43333 return Observable_1.Observable.empty();
43336 return CacheService;
43338 exports.CacheService = CacheService;
43339 exports.default = CacheService;
43341 },{"../Graph":285,"rxjs/Observable":29,"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/delay":56,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/timeout":86}],420:[function(require,module,exports){
43343 Object.defineProperty(exports, "__esModule", { value: true });
43344 var Component_1 = require("../Component");
43345 var ComponentController = /** @class */ (function () {
43346 function ComponentController(container, navigator, observer, key, options, componentService) {
43348 this._container = container;
43349 this._observer = observer;
43350 this._navigator = navigator;
43351 this._options = options != null ? options : {};
43353 this._navigable = key == null;
43354 this._componentService = !!componentService ?
43356 new Component_1.ComponentService(this._container, this._navigator);
43357 this._coverComponent = this._componentService.getCover();
43358 this._initializeComponents();
43360 this._initilizeCoverComponent();
43361 this._subscribeCoverComponent();
43364 this._navigator.movedToKey$
43365 .first(function (k) {
43368 .subscribe(function (k) {
43370 _this._componentService.deactivateCover();
43371 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
43372 _this._subscribeCoverComponent();
43373 _this._navigator.stateService.start();
43374 _this._navigator.cacheService.start();
43375 _this._observer.startEmit();
43379 Object.defineProperty(ComponentController.prototype, "navigable", {
43381 return this._navigable;
43386 ComponentController.prototype.get = function (name) {
43387 return this._componentService.get(name);
43389 ComponentController.prototype.activate = function (name) {
43390 this._componentService.activate(name);
43392 ComponentController.prototype.activateCover = function () {
43393 this._coverComponent.configure({ state: Component_1.CoverState.Visible });
43395 ComponentController.prototype.deactivate = function (name) {
43396 this._componentService.deactivate(name);
43398 ComponentController.prototype.deactivateCover = function () {
43399 this._coverComponent.configure({ state: Component_1.CoverState.Loading });
43401 ComponentController.prototype.resize = function () {
43402 this._componentService.resize();
43404 ComponentController.prototype._initializeComponents = function () {
43405 var options = this._options;
43406 this._uFalse(options.background, "background");
43407 this._uFalse(options.debug, "debug");
43408 this._uFalse(options.image, "image");
43409 this._uFalse(options.marker, "marker");
43410 this._uFalse(options.navigation, "navigation");
43411 this._uFalse(options.popup, "popup");
43412 this._uFalse(options.route, "route");
43413 this._uFalse(options.slider, "slider");
43414 this._uFalse(options.tag, "tag");
43415 this._uTrue(options.attribution, "attribution");
43416 this._uTrue(options.bearing, "bearing");
43417 this._uTrue(options.cache, "cache");
43418 this._uTrue(options.direction, "direction");
43419 this._uTrue(options.imagePlane, "imagePlane");
43420 this._uTrue(options.keyboard, "keyboard");
43421 this._uTrue(options.loading, "loading");
43422 this._uTrue(options.mouse, "mouse");
43423 this._uTrue(options.sequence, "sequence");
43424 this._uTrue(options.stats, "stats");
43426 ComponentController.prototype._initilizeCoverComponent = function () {
43427 var options = this._options;
43428 this._coverComponent.configure({ key: this._key });
43429 if (options.cover === undefined || options.cover) {
43430 this.activateCover();
43433 this.deactivateCover();
43436 ComponentController.prototype._setNavigable = function (navigable) {
43437 if (this._navigable === navigable) {
43440 this._navigable = navigable;
43441 this._observer.navigable$.next(navigable);
43443 ComponentController.prototype._subscribeCoverComponent = function () {
43445 this._coverComponent.configuration$.subscribe(function (conf) {
43446 if (conf.state === Component_1.CoverState.Loading) {
43447 _this._navigator.stateService.currentKey$
43449 .switchMap(function (key) {
43450 var keyChanged = key == null || key !== conf.key;
43452 _this._setNavigable(false);
43454 return keyChanged ?
43455 _this._navigator.moveToKey$(conf.key) :
43456 _this._navigator.stateService.currentNode$
43459 .subscribe(function (node) {
43460 _this._navigator.stateService.start();
43461 _this._navigator.cacheService.start();
43462 _this._observer.startEmit();
43463 _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
43464 _this._componentService.deactivateCover();
43465 _this._setNavigable(true);
43466 }, function (error) {
43467 console.error("Failed to deactivate cover.", error);
43468 _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
43471 else if (conf.state === Component_1.CoverState.Visible) {
43472 _this._observer.stopEmit();
43473 _this._navigator.stateService.stop();
43474 _this._navigator.cacheService.stop();
43475 _this._navigator.playService.stop();
43476 _this._componentService.activateCover();
43477 _this._setNavigable(conf.key == null);
43481 ComponentController.prototype._uFalse = function (option, name) {
43482 if (option === undefined) {
43483 this._componentService.deactivate(name);
43486 if (typeof option === "boolean") {
43488 this._componentService.activate(name);
43491 this._componentService.deactivate(name);
43495 this._componentService.configure(name, option);
43496 this._componentService.activate(name);
43498 ComponentController.prototype._uTrue = function (option, name) {
43499 if (option === undefined) {
43500 this._componentService.activate(name);
43503 if (typeof option === "boolean") {
43505 this._componentService.activate(name);
43508 this._componentService.deactivate(name);
43512 this._componentService.configure(name, option);
43513 this._componentService.activate(name);
43515 return ComponentController;
43517 exports.ComponentController = ComponentController;
43519 },{"../Component":281}],421:[function(require,module,exports){
43521 Object.defineProperty(exports, "__esModule", { value: true });
43522 var Render_1 = require("../Render");
43523 var Utils_1 = require("../Utils");
43524 var Viewer_1 = require("../Viewer");
43525 var Container = /** @class */ (function () {
43526 function Container(id, stateService, options, dom) {
43528 this._dom = !!dom ? dom : new Utils_1.DOM();
43529 this._container = this._dom.document.getElementById(id);
43530 if (!this._container) {
43531 throw new Error("Container '" + id + "' not found.");
43533 this._container.classList.add("mapillary-js");
43534 this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container);
43535 this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container);
43536 this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
43537 this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom);
43538 this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
43539 this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
43540 this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document);
43541 this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
43542 this.spriteService = new Viewer_1.SpriteService(options.sprite);
43544 Object.defineProperty(Container.prototype, "element", {
43546 return this._container;
43551 Object.defineProperty(Container.prototype, "canvasContainer", {
43553 return this._canvasContainer;
43558 Object.defineProperty(Container.prototype, "domContainer", {
43560 return this._domContainer;
43567 exports.Container = Container;
43568 exports.default = Container;
43570 },{"../Render":287,"../Utils":291,"../Viewer":292}],422:[function(require,module,exports){
43572 Object.defineProperty(exports, "__esModule", { value: true });
43574 * Enumeration for image sizes
43577 * @description Image sizes in pixels for the long side of the image.
43580 (function (ImageSize) {
43582 * 320 pixels image size
43584 ImageSize[ImageSize["Size320"] = 320] = "Size320";
43586 * 640 pixels image size
43588 ImageSize[ImageSize["Size640"] = 640] = "Size640";
43590 * 1024 pixels image size
43592 ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
43594 * 2048 pixels image size
43596 ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
43597 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
43599 },{}],423:[function(require,module,exports){
43601 Object.defineProperty(exports, "__esModule", { value: true });
43602 var Observable_1 = require("rxjs/Observable");
43603 var KeyboardService = /** @class */ (function () {
43604 function KeyboardService(canvasContainer) {
43605 this._keyDown$ = Observable_1.Observable.fromEvent(canvasContainer, "keydown");
43607 Object.defineProperty(KeyboardService.prototype, "keyDown$", {
43609 return this._keyDown$;
43614 return KeyboardService;
43616 exports.KeyboardService = KeyboardService;
43617 exports.default = KeyboardService;
43619 },{"rxjs/Observable":29}],424:[function(require,module,exports){
43621 /// <reference path="../../typings/index.d.ts" />
43622 Object.defineProperty(exports, "__esModule", { value: true });
43623 var _ = require("underscore");
43624 var Subject_1 = require("rxjs/Subject");
43625 require("rxjs/add/operator/debounceTime");
43626 require("rxjs/add/operator/distinctUntilChanged");
43627 require("rxjs/add/operator/map");
43628 require("rxjs/add/operator/publishReplay");
43629 require("rxjs/add/operator/scan");
43630 require("rxjs/add/operator/startWith");
43631 var LoadingService = /** @class */ (function () {
43632 function LoadingService() {
43633 this._loadersSubject$ = new Subject_1.Subject();
43634 this._loaders$ = this._loadersSubject$
43635 .scan(function (loaders, loader) {
43636 if (loader.task !== undefined) {
43637 loaders[loader.task] = loader.loading;
43645 Object.defineProperty(LoadingService.prototype, "loading$", {
43647 return this._loaders$
43648 .map(function (loaders) {
43649 return _.reduce(loaders, function (loader, acc) {
43650 return (loader || acc);
43654 .distinctUntilChanged();
43659 LoadingService.prototype.taskLoading$ = function (task) {
43660 return this._loaders$
43661 .map(function (loaders) {
43662 return !!loaders[task];
43665 .distinctUntilChanged();
43667 LoadingService.prototype.startLoading = function (task) {
43668 this._loadersSubject$.next({ loading: true, task: task });
43670 LoadingService.prototype.stopLoading = function (task) {
43671 this._loadersSubject$.next({ loading: false, task: task });
43673 return LoadingService;
43675 exports.LoadingService = LoadingService;
43676 exports.default = LoadingService;
43678 },{"rxjs/Subject":34,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/startWith":80,"underscore":233}],425:[function(require,module,exports){
43680 Object.defineProperty(exports, "__esModule", { value: true });
43681 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
43682 var Observable_1 = require("rxjs/Observable");
43683 var Subject_1 = require("rxjs/Subject");
43684 require("rxjs/add/observable/fromEvent");
43685 require("rxjs/add/operator/distinctUntilChanged");
43686 require("rxjs/add/operator/filter");
43687 require("rxjs/add/operator/map");
43688 require("rxjs/add/operator/merge");
43689 require("rxjs/add/operator/mergeMap");
43690 require("rxjs/add/operator/publishReplay");
43691 require("rxjs/add/operator/scan");
43692 require("rxjs/add/operator/switchMap");
43693 require("rxjs/add/operator/withLatestFrom");
43694 var Geo_1 = require("../Geo");
43695 var MouseService = /** @class */ (function () {
43696 function MouseService(container, canvasContainer, domContainer, doc, viewportCoords) {
43698 viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
43699 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
43700 this._active$ = this._activeSubject$
43701 .distinctUntilChanged()
43704 this._claimMouse$ = new Subject_1.Subject();
43705 this._claimWheel$ = new Subject_1.Subject();
43706 this._deferPixelClaims$ = new Subject_1.Subject();
43707 this._deferPixels$ = this._deferPixelClaims$
43708 .scan(function (claims, claim) {
43709 if (claim.deferPixels == null) {
43710 delete claims[claim.name];
43713 claims[claim.name] = claim.deferPixels;
43717 .map(function (claims) {
43718 var deferPixelMax = -1;
43719 for (var key in claims) {
43720 if (!claims.hasOwnProperty(key)) {
43723 var deferPixels = claims[key];
43724 if (deferPixels > deferPixelMax) {
43725 deferPixelMax = deferPixels;
43728 return deferPixelMax;
43733 this._deferPixels$.subscribe(function () { });
43734 this._documentMouseMove$ = Observable_1.Observable.fromEvent(doc, "mousemove");
43735 this._documentMouseUp$ = Observable_1.Observable.fromEvent(doc, "mouseup");
43736 this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
43737 this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
43738 this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
43739 this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
43740 this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
43741 this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
43742 this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown");
43743 this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove");
43744 this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
43745 this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
43746 this._dblClick$ = Observable_1.Observable
43747 .merge(Observable_1.Observable.fromEvent(container, "click"), Observable_1.Observable.fromEvent(canvasContainer, "dblclick"))
43749 .filter(function (events) {
43750 var event1 = events[0];
43751 var event2 = events[1];
43752 var event3 = events[2];
43753 return event1.type === "click" &&
43754 event2.type === "click" &&
43755 event3.type === "dblclick" &&
43756 event1.target.parentNode === canvasContainer &&
43757 event2.target.parentNode === canvasContainer;
43759 .map(function (events) {
43763 Observable_1.Observable
43764 .merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
43765 .subscribe(function (event) {
43766 event.preventDefault();
43768 this._mouseWheel$ = Observable_1.Observable
43769 .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel"))
43771 this._consistentContextMenu$ = Observable_1.Observable
43772 .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
43774 .filter(function (events) {
43775 // fire context menu on mouse up both on mac and windows
43776 return events[0].type === "mousedown" &&
43777 events[1].type === "contextmenu" &&
43778 events[2].type === "mouseup";
43780 .map(function (events) {
43784 var dragStop$ = Observable_1.Observable
43785 .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$
43786 .filter(function (e) {
43787 return e.button === 0;
43790 var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).share();
43791 this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).share();
43792 this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).share();
43793 this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).share();
43794 var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).share();
43795 this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).share();
43796 this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).share();
43797 this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).share();
43798 this._proximateClick$ = this._mouseDown$
43799 .switchMap(function (mouseDown) {
43800 return _this._click$
43801 .takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$))
43805 this._staticClick$ = this._mouseDown$
43806 .switchMap(function (e) {
43807 return _this._click$
43808 .takeUntil(_this._documentMouseMove$)
43812 this._mouseDragStart$.subscribe();
43813 this._mouseDrag$.subscribe();
43814 this._mouseDragEnd$.subscribe();
43815 this._domMouseDragStart$.subscribe();
43816 this._domMouseDrag$.subscribe();
43817 this._domMouseDragEnd$.subscribe();
43818 this._staticClick$.subscribe();
43819 this._mouseOwner$ = this._createOwner$(this._claimMouse$)
43822 this._wheelOwner$ = this._createOwner$(this._claimWheel$)
43825 this._mouseOwner$.subscribe(function () { });
43826 this._wheelOwner$.subscribe(function () { });
43828 Object.defineProperty(MouseService.prototype, "active$", {
43830 return this._active$;
43835 Object.defineProperty(MouseService.prototype, "activate$", {
43837 return this._activeSubject$;
43842 Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
43844 return this._documentMouseMove$;
43849 Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
43851 return this._documentMouseUp$;
43856 Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
43858 return this._domMouseDragStart$;
43863 Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
43865 return this._domMouseDrag$;
43870 Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
43872 return this._domMouseDragEnd$;
43877 Object.defineProperty(MouseService.prototype, "domMouseDown$", {
43879 return this._domMouseDown$;
43884 Object.defineProperty(MouseService.prototype, "domMouseMove$", {
43886 return this._domMouseMove$;
43891 Object.defineProperty(MouseService.prototype, "mouseOwner$", {
43893 return this._mouseOwner$;
43898 Object.defineProperty(MouseService.prototype, "mouseDown$", {
43900 return this._mouseDown$;
43905 Object.defineProperty(MouseService.prototype, "mouseMove$", {
43907 return this._mouseMove$;
43912 Object.defineProperty(MouseService.prototype, "mouseLeave$", {
43914 return this._mouseLeave$;
43919 Object.defineProperty(MouseService.prototype, "mouseOut$", {
43921 return this._mouseOut$;
43926 Object.defineProperty(MouseService.prototype, "mouseOver$", {
43928 return this._mouseOver$;
43933 Object.defineProperty(MouseService.prototype, "mouseUp$", {
43935 return this._mouseUp$;
43940 Object.defineProperty(MouseService.prototype, "click$", {
43942 return this._click$;
43947 Object.defineProperty(MouseService.prototype, "dblClick$", {
43949 return this._dblClick$;
43954 Object.defineProperty(MouseService.prototype, "contextMenu$", {
43956 return this._consistentContextMenu$;
43961 Object.defineProperty(MouseService.prototype, "mouseWheel$", {
43963 return this._mouseWheel$;
43968 Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
43970 return this._mouseDragStart$;
43975 Object.defineProperty(MouseService.prototype, "mouseDrag$", {
43977 return this._mouseDrag$;
43982 Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
43984 return this._mouseDragEnd$;
43989 Object.defineProperty(MouseService.prototype, "proximateClick$", {
43991 return this._proximateClick$;
43996 Object.defineProperty(MouseService.prototype, "staticClick$", {
43998 return this._staticClick$;
44003 MouseService.prototype.claimMouse = function (name, zindex) {
44004 this._claimMouse$.next({ name: name, zindex: zindex });
44006 MouseService.prototype.unclaimMouse = function (name) {
44007 this._claimMouse$.next({ name: name, zindex: null });
44009 MouseService.prototype.deferPixels = function (name, deferPixels) {
44010 this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
44012 MouseService.prototype.undeferPixels = function (name) {
44013 this._deferPixelClaims$.next({ name: name, deferPixels: null });
44015 MouseService.prototype.claimWheel = function (name, zindex) {
44016 this._claimWheel$.next({ name: name, zindex: zindex });
44018 MouseService.prototype.unclaimWheel = function (name) {
44019 this._claimWheel$.next({ name: name, zindex: null });
44021 MouseService.prototype.filtered$ = function (name, observable$) {
44022 return this._filtered(name, observable$, this._mouseOwner$);
44024 MouseService.prototype.filteredWheel$ = function (name, observable$) {
44025 return this._filtered(name, observable$, this._wheelOwner$);
44027 MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) {
44029 .map(function (mouseMove) {
44030 var deltaX = mouseMove.clientX - origin.clientX;
44031 var deltaY = mouseMove.clientY - origin.clientY;
44032 return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
44034 .withLatestFrom(this._deferPixels$)
44035 .filter(function (_a) {
44036 var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
44037 return delta > deferPixels;
44039 .map(function (_a) {
44040 var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
44044 MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) {
44046 return mouseDragStartInitiate$
44047 .map(function (_a) {
44048 var mouseDown = _a[0], mouseMove = _a[1];
44051 .switchMap(function (mouseMove) {
44052 return Observable_1.Observable
44054 .concat(_this._documentMouseMove$)
44058 MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) {
44059 return mouseDragStart$
44060 .switchMap(function (event) {
44061 return stop$.first();
44064 MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) {
44065 return mouseDragStartInitiate$
44066 .map(function (_a) {
44067 var mouseDown = _a[0], mouseMove = _a[1];
44071 MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) {
44074 .filter(function (mouseDown) {
44075 return mouseDown.button === 0;
44077 .switchMap(function (mouseDown) {
44078 return Observable_1.Observable
44079 .combineLatest(Observable_1.Observable.of(mouseDown), defer ?
44080 _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) :
44081 _this._documentMouseMove$)
44086 MouseService.prototype._createOwner$ = function (claim$) {
44088 .scan(function (claims, claim) {
44089 if (claim.zindex == null) {
44090 delete claims[claim.name];
44093 claims[claim.name] = claim.zindex;
44097 .map(function (claims) {
44099 var zIndexMax = -1;
44100 for (var name_1 in claims) {
44101 if (!claims.hasOwnProperty(name_1)) {
44104 if (claims[name_1] > zIndexMax) {
44105 zIndexMax = claims[name_1];
44113 MouseService.prototype._filtered = function (name, observable$, owner$) {
44115 .withLatestFrom(owner$)
44116 .filter(function (_a) {
44117 var item = _a[0], owner = _a[1];
44118 return owner === name;
44120 .map(function (_a) {
44121 var item = _a[0], owner = _a[1];
44125 return MouseService;
44127 exports.MouseService = MouseService;
44128 exports.default = MouseService;
44130 },{"../Geo":284,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/fromEvent":42,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/switchMap":81,"rxjs/add/operator/withLatestFrom":87}],426:[function(require,module,exports){
44132 /// <reference path="../../typings/index.d.ts" />
44133 Object.defineProperty(exports, "__esModule", { value: true });
44134 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
44135 var Observable_1 = require("rxjs/Observable");
44136 var ReplaySubject_1 = require("rxjs/ReplaySubject");
44137 require("rxjs/add/observable/throw");
44138 require("rxjs/add/operator/do");
44139 require("rxjs/add/operator/finally");
44140 require("rxjs/add/operator/first");
44141 require("rxjs/add/operator/map");
44142 require("rxjs/add/operator/mergeMap");
44143 var API_1 = require("../API");
44144 var Graph_1 = require("../Graph");
44145 var Edge_1 = require("../Edge");
44146 var State_1 = require("../State");
44147 var Viewer_1 = require("../Viewer");
44148 var Navigator = /** @class */ (function () {
44149 function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService, playService) {
44150 this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
44151 this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
44152 this._graphService = graphService != null ?
44154 new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
44155 this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
44156 this._loadingName = "navigator";
44157 this._stateService = stateService != null ? stateService : new State_1.StateService();
44158 this._cacheService = cacheService != null ?
44160 new Viewer_1.CacheService(this._graphService, this._stateService);
44161 this._playService = playService != null ?
44163 new Viewer_1.PlayService(this._graphService, this._stateService);
44164 this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
44165 this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
44166 this._request$ = null;
44167 this._requestSubscription = null;
44168 this._nodeRequestSubscription = null;
44170 Object.defineProperty(Navigator.prototype, "apiV3", {
44172 return this._apiV3;
44177 Object.defineProperty(Navigator.prototype, "cacheService", {
44179 return this._cacheService;
44184 Object.defineProperty(Navigator.prototype, "graphService", {
44186 return this._graphService;
44191 Object.defineProperty(Navigator.prototype, "imageLoadingService", {
44193 return this._imageLoadingService;
44198 Object.defineProperty(Navigator.prototype, "loadingService", {
44200 return this._loadingService;
44205 Object.defineProperty(Navigator.prototype, "movedToKey$", {
44207 return this._movedToKey$;
44212 Object.defineProperty(Navigator.prototype, "playService", {
44214 return this._playService;
44219 Object.defineProperty(Navigator.prototype, "stateService", {
44221 return this._stateService;
44226 Navigator.prototype.moveToKey$ = function (key) {
44227 this._abortRequest("to key " + key);
44228 this._loadingService.startLoading(this._loadingName);
44229 var node$ = this._moveToKey$(key);
44230 return this._makeRequest$(node$);
44232 Navigator.prototype.moveDir$ = function (direction) {
44234 this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
44235 this._loadingService.startLoading(this._loadingName);
44236 var node$ = this.stateService.currentNode$
44238 .mergeMap(function (node) {
44239 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
44240 node.sequenceEdges$ :
44241 node.spatialEdges$)
44243 .map(function (status) {
44244 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
44246 if (edge.data.direction === direction) {
44253 .mergeMap(function (directionKey) {
44254 if (directionKey == null) {
44255 _this._loadingService.stopLoading(_this._loadingName);
44256 return Observable_1.Observable
44257 .throw(new Error("Direction (" + direction + ") does not exist for current node."));
44259 return _this._moveToKey$(directionKey);
44261 return this._makeRequest$(node$);
44263 Navigator.prototype.moveCloseTo$ = function (lat, lon) {
44265 this._abortRequest("to lat " + lat + ", lon " + lon);
44266 this._loadingService.startLoading(this._loadingName);
44267 var node$ = this.apiV3.imageCloseTo$(lat, lon)
44268 .mergeMap(function (fullNode) {
44269 if (fullNode == null) {
44270 _this._loadingService.stopLoading(_this._loadingName);
44271 return Observable_1.Observable
44272 .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
44274 return _this._moveToKey$(fullNode.key);
44276 return this._makeRequest$(node$);
44278 Navigator.prototype.setFilter$ = function (filter) {
44280 this._stateService.clearNodes();
44281 return this._movedToKey$
44283 .mergeMap(function (key) {
44285 return _this._trajectoryKeys$()
44286 .mergeMap(function (keys) {
44287 return _this._graphService.setFilter$(filter)
44288 .mergeMap(function () {
44289 return _this._cacheKeys$(keys);
44294 return _this._keyRequested$
44296 .mergeMap(function (requestedKey) {
44297 if (requestedKey != null) {
44298 return _this._graphService.setFilter$(filter)
44299 .mergeMap(function () {
44300 return _this._graphService.cacheNode$(requestedKey);
44303 return _this._graphService.setFilter$(filter)
44309 .map(function (node) {
44313 Navigator.prototype.setToken$ = function (token) {
44315 this._abortRequest("to set token");
44316 this._stateService.clearNodes();
44317 return this._movedToKey$
44319 .do(function (key) {
44320 _this._apiV3.setToken(token);
44322 .mergeMap(function (key) {
44323 return key == null ?
44324 _this._graphService.reset$([]) :
44325 _this._trajectoryKeys$()
44326 .mergeMap(function (keys) {
44327 return _this._graphService.reset$(keys)
44328 .mergeMap(function () {
44329 return _this._cacheKeys$(keys);
44333 .map(function (node) {
44338 Navigator.prototype._cacheKeys$ = function (keys) {
44340 var cacheNodes$ = keys
44341 .map(function (key) {
44342 return _this._graphService.cacheNode$(key);
44344 return Observable_1.Observable
44348 Navigator.prototype._abortRequest = function (reason) {
44349 if (this._requestSubscription != null) {
44350 this._requestSubscription.unsubscribe();
44351 this._requestSubscription = null;
44353 if (this._nodeRequestSubscription != null) {
44354 this._nodeRequestSubscription.unsubscribe();
44355 this._nodeRequestSubscription = null;
44357 if (this._request$ != null) {
44358 this._request$.error(new Error("Request aborted by a subsequent request " + reason + "."));
44359 this._request$ = null;
44362 Navigator.prototype._makeRequest$ = function (node$) {
44364 this._request$ = new ReplaySubject_1.ReplaySubject(1);
44365 this._requestSubscription = this._request$
44366 .subscribe(undefined, function (e) { });
44367 this._nodeRequestSubscription = node$
44368 .subscribe(function (node) {
44369 _this._request$.next(node);
44370 _this._request$.complete();
44371 }, function (error) {
44372 _this._request$.error(error);
44374 return this._request$;
44376 Navigator.prototype._moveToKey$ = function (key) {
44378 this._keyRequested$.next(key);
44379 return this._graphService.cacheNode$(key)
44380 .do(function (node) {
44381 _this._stateService.setNodes([node]);
44382 _this._movedToKey$.next(node.key);
44384 .finally(function () {
44385 _this._loadingService.stopLoading(_this._loadingName);
44388 Navigator.prototype._trajectoryKeys$ = function () {
44389 return this._stateService.currentState$
44391 .map(function (frame) {
44392 return frame.state.trajectory
44393 .map(function (node) {
44400 exports.Navigator = Navigator;
44401 exports.default = Navigator;
44403 },{"../API":280,"../Edge":282,"../Graph":285,"../State":288,"../Viewer":292,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/ReplaySubject":32,"rxjs/add/observable/throw":46,"rxjs/add/operator/do":59,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68}],427:[function(require,module,exports){
44405 Object.defineProperty(exports, "__esModule", { value: true });
44406 var Observable_1 = require("rxjs/Observable");
44407 var Subject_1 = require("rxjs/Subject");
44408 require("rxjs/add/observable/combineLatest");
44409 require("rxjs/add/operator/distinctUntilChanged");
44410 require("rxjs/add/operator/map");
44411 require("rxjs/add/operator/throttleTime");
44412 var Viewer_1 = require("../Viewer");
44413 var Observer = /** @class */ (function () {
44414 function Observer(eventEmitter, navigator, container) {
44416 this._container = container;
44417 this._eventEmitter = eventEmitter;
44418 this._navigator = navigator;
44419 this._projection = new Viewer_1.Projection();
44420 this._started = false;
44421 this._navigable$ = new Subject_1.Subject();
44422 // navigable and loading should always emit, also when cover is activated.
44424 .subscribe(function (navigable) {
44425 _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
44427 this._navigator.loadingService.loading$
44428 .subscribe(function (loading) {
44429 _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
44432 Object.defineProperty(Observer.prototype, "started", {
44434 return this._started;
44439 Object.defineProperty(Observer.prototype, "navigable$", {
44441 return this._navigable$;
44446 Observer.prototype.projectBasic$ = function (basicPoint) {
44448 return Observable_1.Observable
44449 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
44451 .map(function (_a) {
44452 var render = _a[0], transform = _a[1];
44453 var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
44454 return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
44457 Observer.prototype.startEmit = function () {
44459 if (this._started) {
44462 this._started = true;
44463 this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
44464 .subscribe(function (node) {
44465 _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
44467 this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
44468 .switchMap(function (node) {
44469 return node.sequenceEdges$;
44471 .subscribe(function (status) {
44472 _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
44474 this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
44475 .switchMap(function (node) {
44476 return node.spatialEdges$;
44478 .subscribe(function (status) {
44479 _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
44481 this._moveSubscription = Observable_1.Observable
44482 .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
44483 .map(function (values) {
44484 return values[0] || values[1] || values[2];
44486 .distinctUntilChanged()
44487 .subscribe(function (started) {
44489 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
44492 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
44495 this._bearingSubscription = this._container.renderService.bearing$
44497 .distinctUntilChanged(function (b1, b2) {
44498 return Math.abs(b2 - b1) < 1;
44500 .subscribe(function (bearing) {
44501 _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
44503 var mouseMove$ = this._container.mouseService.active$
44504 .switchMap(function (active) {
44506 Observable_1.Observable.empty() :
44507 _this._container.mouseService.mouseMove$;
44509 this._viewerMouseEventSubscription = Observable_1.Observable
44510 .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$))
44511 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
44512 .map(function (_a) {
44513 var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
44514 var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
44516 basicPoint: unprojection.basicPoint,
44517 latLon: unprojection.latLon,
44518 originalEvent: event,
44519 pixelPoint: unprojection.pixelPoint,
44520 target: _this._eventEmitter,
44524 .subscribe(function (event) {
44525 _this._eventEmitter.fire(event.type, event);
44528 Observer.prototype.stopEmit = function () {
44529 if (!this.started) {
44532 this._started = false;
44533 this._bearingSubscription.unsubscribe();
44534 this._currentNodeSubscription.unsubscribe();
44535 this._moveSubscription.unsubscribe();
44536 this._sequenceEdgesSubscription.unsubscribe();
44537 this._spatialEdgesSubscription.unsubscribe();
44538 this._viewerMouseEventSubscription.unsubscribe();
44539 this._bearingSubscription = null;
44540 this._currentNodeSubscription = null;
44541 this._moveSubscription = null;
44542 this._sequenceEdgesSubscription = null;
44543 this._spatialEdgesSubscription = null;
44544 this._viewerMouseEventSubscription = null;
44546 Observer.prototype.unproject$ = function (canvasPoint) {
44548 return Observable_1.Observable
44549 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
44551 .map(function (_a) {
44552 var render = _a[0], reference = _a[1], transform = _a[2];
44553 var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
44554 return unprojection.latLon;
44557 Observer.prototype.unprojectBasic$ = function (canvasPoint) {
44559 return Observable_1.Observable
44560 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
44562 .map(function (_a) {
44563 var render = _a[0], transform = _a[1];
44564 return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
44567 Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
44568 return mouseEvent$.map(function (event) {
44569 return [type, event];
44574 exports.Observer = Observer;
44575 exports.default = Observer;
44577 },{"../Viewer":292,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/throttleTime":85}],428:[function(require,module,exports){
44579 Object.defineProperty(exports, "__esModule", { value: true });
44580 var Observable_1 = require("rxjs/Observable");
44581 var Subject_1 = require("rxjs/Subject");
44582 require("rxjs/add/operator/timeout");
44583 var Edge_1 = require("../Edge");
44584 var Graph_1 = require("../Graph");
44585 var PlayService = /** @class */ (function () {
44586 function PlayService(graphService, stateService) {
44587 this._graphService = graphService;
44588 this._stateService = stateService;
44589 this._directionSubject$ = new Subject_1.Subject();
44590 this._direction$ = this._directionSubject$
44591 .startWith(Edge_1.EdgeDirection.Next)
44594 this._direction$.subscribe();
44595 this._playing = false;
44596 this._playingSubject$ = new Subject_1.Subject();
44597 this._playing$ = this._playingSubject$
44598 .startWith(this._playing)
44601 this._playing$.subscribe();
44603 this._speedSubject$ = new Subject_1.Subject();
44604 this._speed$ = this._speedSubject$
44605 .startWith(this._speed)
44608 this._speed$.subscribe();
44609 this._nodesAhead = this._mapNodesAhead(this._mapSpeed(this._speed));
44611 Object.defineProperty(PlayService.prototype, "playing", {
44613 return this._playing;
44618 Object.defineProperty(PlayService.prototype, "direction$", {
44620 return this._direction$;
44625 Object.defineProperty(PlayService.prototype, "playing$", {
44627 return this._playing$;
44632 Object.defineProperty(PlayService.prototype, "speed$", {
44634 return this._speed$;
44639 PlayService.prototype.play = function () {
44641 if (this._playing) {
44644 this._stateService.cutNodes();
44645 var stateSpeed = this._setSpeed(this._speed);
44646 this._stateService.setSpeed(stateSpeed);
44647 this._graphModeSubscription = this._speed$
44648 .map(function (speed) {
44649 return speed > 0.54 ? Graph_1.GraphMode.Sequence : Graph_1.GraphMode.Spatial;
44651 .distinctUntilChanged()
44652 .subscribe(function (mode) {
44653 _this._graphService.setGraphMode(mode);
44655 this._cacheSubscription = this._stateService.currentNode$
44656 .map(function (node) {
44657 return [node.sequenceKey, node.key];
44659 .distinctUntilChanged(undefined, function (_a) {
44660 var sequenceKey = _a[0], nodeKey = _a[1];
44661 return sequenceKey;
44663 .combineLatest(this._graphService.graphMode$, this._direction$)
44664 .switchMap(function (_a) {
44665 var _b = _a[0], sequenceKey = _b[0], nodeKey = _b[1], mode = _a[1], direction = _a[2];
44666 if (direction !== Edge_1.EdgeDirection.Next && direction !== Edge_1.EdgeDirection.Prev) {
44667 return Observable_1.Observable.of([undefined, direction]);
44669 var sequence$ = (mode === Graph_1.GraphMode.Sequence ?
44670 _this._graphService.cacheSequenceNodes$(sequenceKey, nodeKey) :
44671 _this._graphService.cacheSequence$(sequenceKey))
44673 .catch(function () {
44674 return Observable_1.Observable.of(undefined);
44676 return Observable_1.Observable
44677 .combineLatest(sequence$, Observable_1.Observable.of(direction));
44679 .switchMap(function (_a) {
44680 var sequence = _a[0], direction = _a[1];
44681 if (sequence === undefined) {
44682 return Observable_1.Observable.empty();
44684 var sequenceKeys = sequence.keys.slice();
44685 if (direction === Edge_1.EdgeDirection.Prev) {
44686 sequenceKeys.reverse();
44688 return _this._stateService.currentState$
44689 .map(function (frame) {
44690 return [frame.state.trajectory[frame.state.trajectory.length - 1].key, frame.state.nodesAhead];
44692 .scan(function (_a, _b) {
44693 var lastRequestKey = _a[0], previousRequestKeys = _a[1];
44694 var lastTrajectoryKey = _b[0], nodesAhead = _b[1];
44695 if (lastRequestKey === undefined) {
44696 lastRequestKey = lastTrajectoryKey;
44698 var lastIndex = sequenceKeys.length - 1;
44699 if (nodesAhead >= _this._nodesAhead || sequenceKeys[lastIndex] === lastRequestKey) {
44700 return [lastRequestKey, []];
44702 var current = sequenceKeys.indexOf(lastTrajectoryKey);
44703 var start = sequenceKeys.indexOf(lastRequestKey) + 1;
44704 var end = Math.min(lastIndex, current + _this._nodesAhead - nodesAhead) + 1;
44705 if (end <= start) {
44706 return [lastRequestKey, []];
44708 return [sequenceKeys[end - 1], sequenceKeys.slice(start, end)];
44709 }, [undefined, []])
44710 .mergeMap(function (_a) {
44711 var lastRequestKey = _a[0], newRequestKeys = _a[1];
44712 return Observable_1.Observable.from(newRequestKeys);
44715 .mergeMap(function (key) {
44716 return _this._graphService.cacheNode$(key)
44717 .catch(function () {
44718 return Observable_1.Observable.empty();
44722 this._playingSubscription = this._stateService.currentState$
44723 .filter(function (frame) {
44724 return frame.state.nodesAhead < _this._nodesAhead;
44726 .map(function (frame) {
44727 return frame.state.lastNode;
44729 .distinctUntilChanged(undefined, function (lastNode) {
44730 return lastNode.key;
44732 .withLatestFrom(this._direction$)
44733 .switchMap(function (_a) {
44734 var node = _a[0], direction = _a[1];
44735 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
44736 node.sequenceEdges$ :
44737 node.spatialEdges$)
44738 .first(function (status) {
44739 return status.cached;
44742 .zip(Observable_1.Observable.of(direction))
44743 .map(function (_a) {
44744 var s = _a[0], d = _a[1];
44745 for (var _i = 0, _b = s.edges; _i < _b.length; _i++) {
44747 if (edge.data.direction === d) {
44753 .filter(function (key) {
44754 return key != null;
44756 .switchMap(function (key) {
44757 return _this._graphService.cacheNode$(key);
44760 .subscribe(function (node) {
44761 _this._stateService.appendNodes([node]);
44762 }, function (error) {
44763 console.error(error);
44766 this._clearSubscription = this._stateService.currentNode$
44767 .bufferCount(1, 10)
44768 .subscribe(function (nodes) {
44769 _this._stateService.clearPriorNodes();
44771 this._setPlaying(true);
44772 this._stopSubscription = Observable_1.Observable
44773 .combineLatest(this._stateService.currentNode$, this._direction$)
44774 .switchMap(function (_a) {
44775 var node = _a[0], direction = _a[1];
44776 var edgeStatus$ = ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
44777 node.sequenceEdges$ :
44778 node.spatialEdges$)
44779 .first(function (status) {
44780 return status.cached;
44783 .catch(function (error) {
44784 console.error(error);
44785 return Observable_1.Observable.of({ cached: false, edges: [] });
44787 return Observable_1.Observable
44788 .combineLatest(Observable_1.Observable.of(direction), edgeStatus$);
44790 .map(function (_a) {
44791 var direction = _a[0], edgeStatus = _a[1];
44792 for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
44794 if (edge.data.direction === direction) {
44800 .first(function (hasEdge) {
44803 .subscribe(undefined, undefined, function () { _this.stop(); });
44804 if (this._stopSubscription.closed) {
44805 this._stopSubscription = null;
44808 PlayService.prototype.setDirection = function (direction) {
44809 this._directionSubject$.next(direction);
44811 PlayService.prototype.setSpeed = function (speed) {
44812 speed = Math.max(0, Math.min(1, speed));
44813 if (speed === this._speed) {
44816 var stateSpeed = this._setSpeed(speed);
44817 if (this._playing) {
44818 this._stateService.setSpeed(stateSpeed);
44820 this._speedSubject$.next(this._speed);
44822 PlayService.prototype.stop = function () {
44823 if (!this._playing) {
44826 if (!!this._stopSubscription) {
44827 if (!this._stopSubscription.closed) {
44828 this._stopSubscription.unsubscribe();
44830 this._stopSubscription = null;
44832 this._graphModeSubscription.unsubscribe();
44833 this._graphModeSubscription = null;
44834 this._cacheSubscription.unsubscribe();
44835 this._cacheSubscription = null;
44836 this._playingSubscription.unsubscribe();
44837 this._playingSubscription = null;
44838 this._clearSubscription.unsubscribe();
44839 this._clearSubscription = null;
44840 this._stateService.setSpeed(1);
44841 this._stateService.cutNodes();
44842 this._graphService.setGraphMode(Graph_1.GraphMode.Spatial);
44843 this._setPlaying(false);
44845 PlayService.prototype._mapSpeed = function (speed) {
44846 var x = 2 * speed - 1;
44847 return Math.pow(10, x) - 0.2 * x;
44849 PlayService.prototype._mapNodesAhead = function (stateSpeed) {
44850 return Math.round(Math.max(10, Math.min(50, 8 + 6 * stateSpeed)));
44852 PlayService.prototype._setPlaying = function (playing) {
44853 this._playing = playing;
44854 this._playingSubject$.next(playing);
44856 PlayService.prototype._setSpeed = function (speed) {
44857 this._speed = speed;
44858 var stateSpeed = this._mapSpeed(this._speed);
44859 this._nodesAhead = this._mapNodesAhead(stateSpeed);
44862 return PlayService;
44864 exports.PlayService = PlayService;
44865 exports.default = PlayService;
44867 },{"../Edge":282,"../Graph":285,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/timeout":86}],429:[function(require,module,exports){
44869 /// <reference path="../../typings/index.d.ts" />
44870 Object.defineProperty(exports, "__esModule", { value: true });
44871 var THREE = require("three");
44872 var Geo_1 = require("../Geo");
44873 var Projection = /** @class */ (function () {
44874 function Projection(geoCoords, viewportCoords) {
44875 this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
44876 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
44878 Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
44879 return this._viewportCoords
44880 .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
44882 Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
44883 var basicPoint = this._viewportCoords
44884 .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
44885 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
44890 Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
44891 var pixelPoint = this._viewportCoords.canvasPosition(event, container);
44892 return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
44894 Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
44895 var canvasX = canvasPoint[0];
44896 var canvasY = canvasPoint[1];
44897 var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
44898 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
44899 .unproject(render.perspective);
44900 var basicPoint = transform.projectBasic(point3d.toArray());
44901 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
44904 var direction3d = point3d.clone().sub(render.camera.position).normalize();
44905 var dist = -2 / direction3d.z;
44907 if (dist > 0 && dist < 100 && !!basicPoint) {
44908 var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
44909 var latLonArray = this._geoCoords
44910 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
44912 latLon = { lat: latLonArray[0], lon: latLonArray[1] };
44914 var unprojection = {
44915 basicPoint: basicPoint,
44917 pixelPoint: [canvasX, canvasY],
44919 return unprojection;
44923 exports.Projection = Projection;
44924 exports.default = Projection;
44926 },{"../Geo":284,"three":231}],430:[function(require,module,exports){
44928 /// <reference path="../../typings/index.d.ts" />
44929 Object.defineProperty(exports, "__esModule", { value: true });
44930 var THREE = require("three");
44931 var vd = require("virtual-dom");
44932 var Subject_1 = require("rxjs/Subject");
44933 require("rxjs/add/operator/publishReplay");
44934 require("rxjs/add/operator/scan");
44935 require("rxjs/add/operator/startWith");
44936 var Viewer_1 = require("../Viewer");
44937 var SpriteAtlas = /** @class */ (function () {
44938 function SpriteAtlas() {
44940 Object.defineProperty(SpriteAtlas.prototype, "json", {
44941 set: function (value) {
44942 this._json = value;
44947 Object.defineProperty(SpriteAtlas.prototype, "image", {
44948 set: function (value) {
44949 this._image = value;
44950 this._texture = new THREE.Texture(this._image);
44951 this._texture.minFilter = THREE.NearestFilter;
44956 Object.defineProperty(SpriteAtlas.prototype, "loaded", {
44958 return !!(this._image && this._json);
44963 SpriteAtlas.prototype.getGLSprite = function (name) {
44964 if (!this.loaded) {
44965 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
44967 var definition = this._json[name];
44969 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
44970 return new THREE.Object3D();
44972 var texture = this._texture.clone();
44973 texture.needsUpdate = true;
44974 var width = this._image.width;
44975 var height = this._image.height;
44976 texture.offset.x = definition.x / width;
44977 texture.offset.y = (height - definition.y - definition.height) / height;
44978 texture.repeat.x = definition.width / width;
44979 texture.repeat.y = definition.height / height;
44980 var material = new THREE.SpriteMaterial({ map: texture });
44981 return new THREE.Sprite(material);
44983 SpriteAtlas.prototype.getDOMSprite = function (name, float) {
44984 if (!this.loaded) {
44985 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
44987 if (float == null) {
44988 float = Viewer_1.Alignment.Center;
44990 var definition = this._json[name];
44992 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
44993 return vd.h("div", {}, []);
44995 var clipTop = definition.y;
44996 var clipRigth = definition.x + definition.width;
44997 var clipBottom = definition.y + definition.height;
44998 var clipLeft = definition.x;
44999 var left = -definition.x;
45000 var top = -definition.y;
45001 var height = this._image.height;
45002 var width = this._image.width;
45004 case Viewer_1.Alignment.Bottom:
45005 case Viewer_1.Alignment.Center:
45006 case Viewer_1.Alignment.Top:
45007 left -= definition.width / 2;
45009 case Viewer_1.Alignment.BottomLeft:
45010 case Viewer_1.Alignment.Left:
45011 case Viewer_1.Alignment.TopLeft:
45012 left -= definition.width;
45014 case Viewer_1.Alignment.BottomRight:
45015 case Viewer_1.Alignment.Right:
45016 case Viewer_1.Alignment.TopRight:
45021 case Viewer_1.Alignment.Center:
45022 case Viewer_1.Alignment.Left:
45023 case Viewer_1.Alignment.Right:
45024 top -= definition.height / 2;
45026 case Viewer_1.Alignment.Top:
45027 case Viewer_1.Alignment.TopLeft:
45028 case Viewer_1.Alignment.TopRight:
45029 top -= definition.height;
45031 case Viewer_1.Alignment.Bottom:
45032 case Viewer_1.Alignment.BottomLeft:
45033 case Viewer_1.Alignment.BottomRight:
45037 var pixelRatioInverse = 1 / definition.pixelRatio;
45038 clipTop *= pixelRatioInverse;
45039 clipRigth *= pixelRatioInverse;
45040 clipBottom *= pixelRatioInverse;
45041 clipLeft *= pixelRatioInverse;
45042 left *= pixelRatioInverse;
45043 top *= pixelRatioInverse;
45044 height *= pixelRatioInverse;
45045 width *= pixelRatioInverse;
45047 src: this._image.src,
45049 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
45050 height: height + "px",
45052 position: "absolute",
45054 width: width + "px",
45057 return vd.h("img", properties, []);
45059 return SpriteAtlas;
45061 var SpriteService = /** @class */ (function () {
45062 function SpriteService(sprite) {
45064 this._retina = window.devicePixelRatio > 1;
45065 this._spriteAtlasOperation$ = new Subject_1.Subject();
45066 this._spriteAtlas$ = this._spriteAtlasOperation$
45067 .startWith(function (atlas) {
45070 .scan(function (atlas, operation) {
45071 return operation(atlas);
45072 }, new SpriteAtlas())
45075 this._spriteAtlas$.subscribe(function () { });
45076 if (sprite == null) {
45079 var format = this._retina ? "@2x" : "";
45080 var imageXmlHTTP = new XMLHttpRequest();
45081 imageXmlHTTP.open("GET", sprite + format + ".png", true);
45082 imageXmlHTTP.responseType = "arraybuffer";
45083 imageXmlHTTP.onload = function () {
45084 var image = new Image();
45085 image.onload = function () {
45086 _this._spriteAtlasOperation$.next(function (atlas) {
45087 atlas.image = image;
45091 var blob = new Blob([imageXmlHTTP.response]);
45092 image.src = window.URL.createObjectURL(blob);
45094 imageXmlHTTP.onerror = function (error) {
45095 console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
45097 imageXmlHTTP.send();
45098 var jsonXmlHTTP = new XMLHttpRequest();
45099 jsonXmlHTTP.open("GET", sprite + format + ".json", true);
45100 jsonXmlHTTP.responseType = "text";
45101 jsonXmlHTTP.onload = function () {
45102 var json = JSON.parse(jsonXmlHTTP.response);
45103 _this._spriteAtlasOperation$.next(function (atlas) {
45108 jsonXmlHTTP.onerror = function (error) {
45109 console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
45111 jsonXmlHTTP.send();
45113 Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
45115 return this._spriteAtlas$;
45120 return SpriteService;
45122 exports.SpriteService = SpriteService;
45123 exports.default = SpriteService;
45125 },{"../Viewer":292,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":75,"rxjs/add/operator/startWith":80,"three":231,"virtual-dom":237}],431:[function(require,module,exports){
45127 Object.defineProperty(exports, "__esModule", { value: true });
45128 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
45129 var Observable_1 = require("rxjs/Observable");
45130 var Subject_1 = require("rxjs/Subject");
45131 require("rxjs/add/observable/timer");
45132 require("rxjs/add/operator/bufferWhen");
45133 require("rxjs/add/operator/filter");
45134 require("rxjs/add/operator/map");
45135 require("rxjs/add/operator/merge");
45136 require("rxjs/add/operator/scan");
45137 require("rxjs/add/operator/switchMap");
45138 var TouchService = /** @class */ (function () {
45139 function TouchService(canvasContainer, domContainer) {
45141 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
45142 this._active$ = this._activeSubject$
45143 .distinctUntilChanged()
45146 Observable_1.Observable.fromEvent(domContainer, "touchmove")
45147 .subscribe(function (event) {
45148 event.preventDefault();
45150 this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart");
45151 this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove");
45152 this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend");
45153 this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel");
45154 var tapStart$ = this._touchStart$
45155 .filter(function (te) {
45156 return te.touches.length === 1 && te.targetTouches.length === 1;
45159 this._doubleTap$ = tapStart$
45160 .bufferWhen(function () {
45163 .switchMap(function (event) {
45164 return Observable_1.Observable
45170 .filter(function (events) {
45171 return events.length === 2;
45173 .map(function (events) {
45174 return events[events.length - 1];
45178 .subscribe(function (event) {
45179 event.preventDefault();
45181 this._singleTouchMove$ = this._touchMove$
45182 .filter(function (te) {
45183 return te.touches.length === 1 && te.targetTouches.length === 1;
45186 var singleTouchStart$ = Observable_1.Observable
45187 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
45188 .filter(function (te) {
45189 return te.touches.length === 1 && te.targetTouches.length === 1;
45191 var multipleTouchStart$ = Observable_1.Observable
45192 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
45193 .filter(function (te) {
45194 return te.touches.length >= 1;
45196 var touchStop$ = Observable_1.Observable
45197 .merge(this._touchEnd$, this._touchCancel$)
45198 .filter(function (te) {
45199 return te.touches.length === 0;
45201 this._singleTouchDragStart$ = singleTouchStart$
45202 .mergeMap(function (e) {
45203 return _this._singleTouchMove$
45204 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
45207 this._singleTouchDragEnd$ = singleTouchStart$
45208 .mergeMap(function (e) {
45209 return Observable_1.Observable
45210 .merge(touchStop$, multipleTouchStart$)
45213 this._singleTouchDrag$ = singleTouchStart$
45214 .switchMap(function (te) {
45215 return _this._singleTouchMove$
45217 .takeUntil(Observable_1.Observable
45218 .merge(multipleTouchStart$, touchStop$));
45220 var touchesChanged$ = Observable_1.Observable
45221 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
45222 this._pinchStart$ = touchesChanged$
45223 .filter(function (te) {
45224 return te.touches.length === 2 && te.targetTouches.length === 2;
45226 this._pinchEnd$ = touchesChanged$
45227 .filter(function (te) {
45228 return te.touches.length !== 2 || te.targetTouches.length !== 2;
45230 this._pinchOperation$ = new Subject_1.Subject();
45231 this._pinch$ = this._pinchOperation$
45232 .scan(function (pinch, operation) {
45233 return operation(pinch);
45243 originalEvent: null,
45252 .filter(function (te) {
45253 return te.touches.length === 2 && te.targetTouches.length === 2;
45255 .map(function (te) {
45256 return function (previous) {
45257 var touch1 = te.touches[0];
45258 var touch2 = te.touches[1];
45259 var minX = Math.min(touch1.clientX, touch2.clientX);
45260 var maxX = Math.max(touch1.clientX, touch2.clientX);
45261 var minY = Math.min(touch1.clientY, touch2.clientY);
45262 var maxY = Math.max(touch1.clientY, touch2.clientY);
45263 var centerClientX = minX + (maxX - minX) / 2;
45264 var centerClientY = minY + (maxY - minY) / 2;
45265 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
45266 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
45267 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
45268 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
45269 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
45270 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
45271 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
45272 var distanceChange = distance - previous.distance;
45273 var changeX = distanceX - previous.distanceX;
45274 var changeY = distanceY - previous.distanceY;
45278 clientX: centerClientX,
45279 clientY: centerClientY,
45280 distance: distance,
45281 distanceChange: distanceChange,
45282 distanceX: distanceX,
45283 distanceY: distanceY,
45285 pageX: centerPageX,
45286 pageY: centerPageY,
45287 screenX: centerScreenX,
45288 screenY: centerScreenY,
45295 .subscribe(this._pinchOperation$);
45296 this._pinchChange$ = this._pinchStart$
45297 .switchMap(function (te) {
45298 return _this._pinch$
45300 .takeUntil(_this._pinchEnd$);
45303 Object.defineProperty(TouchService.prototype, "active$", {
45305 return this._active$;
45310 Object.defineProperty(TouchService.prototype, "activate$", {
45312 return this._activeSubject$;
45317 Object.defineProperty(TouchService.prototype, "doubleTap$", {
45319 return this._doubleTap$;
45324 Object.defineProperty(TouchService.prototype, "touchStart$", {
45326 return this._touchStart$;
45331 Object.defineProperty(TouchService.prototype, "touchMove$", {
45333 return this._touchMove$;
45338 Object.defineProperty(TouchService.prototype, "touchEnd$", {
45340 return this._touchEnd$;
45345 Object.defineProperty(TouchService.prototype, "touchCancel$", {
45347 return this._touchCancel$;
45352 Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
45354 return this._singleTouchDragStart$;
45359 Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
45361 return this._singleTouchDrag$;
45366 Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
45368 return this._singleTouchDragEnd$;
45373 Object.defineProperty(TouchService.prototype, "pinch$", {
45375 return this._pinchChange$;
45380 Object.defineProperty(TouchService.prototype, "pinchStart$", {
45382 return this._pinchStart$;
45387 Object.defineProperty(TouchService.prototype, "pinchEnd$", {
45389 return this._pinchEnd$;
45394 return TouchService;
45396 exports.TouchService = TouchService;
45398 },{"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/timer":47,"rxjs/add/operator/bufferWhen":51,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/scan":75,"rxjs/add/operator/switchMap":81}],432:[function(require,module,exports){
45400 /// <reference path="../../typings/index.d.ts" />
45401 var __extends = (this && this.__extends) || (function () {
45402 var extendStatics = Object.setPrototypeOf ||
45403 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45404 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45405 return function (d, b) {
45406 extendStatics(d, b);
45407 function __() { this.constructor = d; }
45408 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45411 Object.defineProperty(exports, "__esModule", { value: true });
45412 var when = require("when");
45413 var Observable_1 = require("rxjs/Observable");
45414 var Viewer_1 = require("../Viewer");
45415 var Utils_1 = require("../Utils");
45419 * @classdesc The Viewer object represents the navigable image viewer.
45420 * Create a Viewer by specifying a container, client ID, image key and
45421 * other options. The viewer exposes methods and events for programmatic
45424 * The viewer works with a few different coordinate systems.
45426 * Container pixel coordinates
45428 * Pixel coordinates are coordinates on the viewer container. The origin is
45429 * in the top left corner of the container. The axes are
45430 * directed according to the following for a viewer container with a width
45431 * of 640 pixels and height of 480 pixels.
45435 * +------------------------>
45440 * (0, 480) (640, 480)
45443 * Basic image coordinates
45445 * Basic image coordinates represents points in the original image adjusted for
45446 * orientation. They range from 0 to 1 on both axes. The origin is in the top left
45447 * corner of the image and the axes are directed
45448 * according to the following for all image types.
45452 * +------------------------>
45460 * For every camera viewing direction it is possible to convert between these
45461 * two coordinate systems for the current node. The image can be panned and
45462 * zoomed independently of the size of the viewer container resulting in
45463 * different conversion results for different viewing directions.
45465 var Viewer = /** @class */ (function (_super) {
45466 __extends(Viewer, _super);
45468 * Create a new viewer instance.
45470 * @description It is possible to initialize the viewer with or
45473 * When initializing with a key the viewer is bound to that key
45474 * until the node/image for that key has been successfully loaded.
45475 * Also, a cover with the image of the key will be shown.
45476 * If the data for that key can not be loaded because the key is
45477 * faulty or other errors occur it is not possible to navigate
45478 * to another key because the viewer is not navigable. The viewer
45479 * becomes navigable when the data for the has been loaded and
45480 * the image is shown in the viewer. This wayof initializing
45481 * the viewer is mostly for embedding in blog posts and similar
45482 * where one wants to show a specific image initially.
45484 * If the viewer is initialized without a key (with null or
45485 * undefined) it is not bound to any particular key and it is
45486 * possible to move to any key with `viewer.moveToKey("<my-image-key>")`.
45487 * If the first move to a key fails it is possible to move to another
45488 * key. The viewer will show a black background until a move
45489 * succeeds. This way of intitializing is suited for a map-viewer
45490 * application when the initial key is not known at implementation
45493 * @param {string} id - Required `id` of a DOM element which will
45494 * be transformed into the viewer.
45495 * @param {string} clientId - Required `Mapillary API ClientID`. Can
45496 * be obtained from https://www.mapillary.com/app/settings/developers.
45497 * @param {string} key - Optional `image-key` to start from. The key
45498 * can be any Mapillary image. If a key is provided the viewer is
45499 * bound to that key until it has been fully loaded. If null is provided
45500 * no image is loaded at viewer initialization and the viewer is not
45501 * bound to any particular key. Any image can then be navigated to
45502 * with e.g. `viewer.moveToKey("<my-image-key>")`.
45503 * @param {IViewerOptions} options - Optional configuration object
45504 * specifing Viewer's and the components' initial setup.
45505 * @param {string} token - Optional bearer token for API requests of
45506 * protected resources.
45510 * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<image-key>");
45513 function Viewer(id, clientId, key, options, token) {
45514 var _this = _super.call(this) || this;
45515 options = options != null ? options : {};
45516 Utils_1.Settings.setOptions(options);
45517 _this._navigator = new Viewer_1.Navigator(clientId, token);
45518 _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
45519 _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
45520 _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
45523 Object.defineProperty(Viewer.prototype, "isNavigable", {
45525 * Return a boolean indicating if the viewer is in a navigable state.
45527 * @description The navigable state indicates if the viewer supports
45528 * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
45529 * methods. The viewer will not be in a navigable state if the cover
45530 * is activated and the viewer has been supplied a key. When the cover
45531 * is deactivated or activated without being supplied a key it will
45534 * @returns {boolean} Boolean indicating whether the viewer is navigable.
45537 return this._componentController.navigable;
45543 * Activate a component.
45545 * @param {string} name - Name of the component which will become active.
45549 * viewer.activateComponent("marker");
45552 Viewer.prototype.activateComponent = function (name) {
45553 this._componentController.activate(name);
45556 * Activate the cover (deactivates all other components).
45558 Viewer.prototype.activateCover = function () {
45559 this._componentController.activateCover();
45562 * Deactivate a component.
45564 * @param {string} name - Name of component which become inactive.
45568 * viewer.deactivateComponent("mouse");
45571 Viewer.prototype.deactivateComponent = function (name) {
45572 this._componentController.deactivate(name);
45575 * Deactivate the cover (activates all components marked as active).
45577 Viewer.prototype.deactivateCover = function () {
45578 this._componentController.deactivateCover();
45581 * Get the bearing of the current viewer camera.
45583 * @description The bearing depends on how the camera
45584 * is currently rotated and does not correspond
45585 * to the compass angle of the current node if the view
45588 * Bearing is measured in degrees clockwise with respect to
45591 * @returns {Promise<number>} Promise to the bearing
45592 * of the current viewer camera.
45596 * viewer.getBearing().then((b) => { console.log(b); });
45599 Viewer.prototype.getBearing = function () {
45601 return when.promise(function (resolve, reject) {
45602 _this._container.renderService.bearing$
45604 .subscribe(function (bearing) {
45606 }, function (error) {
45612 * Get the basic coordinates of the current image that is
45613 * at the center of the viewport.
45615 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
45616 * and have the origin point, (0, 0), at the top left corner and the
45617 * maximum value, (1, 1), at the bottom right corner of the original
45620 * @returns {Promise<number[]>} Promise to the basic coordinates
45621 * of the current image at the center for the viewport.
45625 * viewer.getCenter().then((c) => { console.log(c); });
45628 Viewer.prototype.getCenter = function () {
45630 return when.promise(function (resolve, reject) {
45631 _this._navigator.stateService.getCenter()
45632 .subscribe(function (center) {
45634 }, function (error) {
45642 * @param {string} name - Name of component.
45643 * @returns {Component} The requested component.
45647 * var mouseComponent = viewer.getComponent("mouse");
45650 Viewer.prototype.getComponent = function (name) {
45651 return this._componentController.get(name);
45654 * Returns the viewer's containing HTML element.
45656 * @returns {HTMLElement} The viewer's container.
45658 Viewer.prototype.getContainer = function () {
45659 return this._container.element;
45662 * Get the image's current zoom level.
45664 * @returns {Promise<number>} Promise to the viewers's current
45669 * viewer.getZoom().then((z) => { console.log(z); });
45672 Viewer.prototype.getZoom = function () {
45674 return when.promise(function (resolve, reject) {
45675 _this._navigator.stateService.getZoom()
45676 .subscribe(function (zoom) {
45678 }, function (error) {
45684 * Move close to given latitude and longitude.
45686 * @description Because the method propagates IO errors, these potential errors
45687 * need to be handled by the method caller (see example).
45689 * @param {Number} lat - Latitude, in degrees.
45690 * @param {Number} lon - Longitude, in degrees.
45691 * @returns {Promise<Node>} Promise to the node that was navigated to.
45692 * @throws {Error} If no nodes exist close to provided latitude
45694 * @throws {Error} Propagates any IO errors to the caller.
45695 * @throws {Error} When viewer is not navigable.
45699 * viewer.moveCloseTo(0, 0).then(
45700 * (n) => { console.log(n); },
45701 * (e) => { console.error(e); });
45704 Viewer.prototype.moveCloseTo = function (lat, lon) {
45705 var moveCloseTo$ = this.isNavigable ?
45706 this._navigator.moveCloseTo$(lat, lon) :
45707 Observable_1.Observable.throw(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
45708 return when.promise(function (resolve, reject) {
45709 moveCloseTo$.subscribe(function (node) {
45711 }, function (error) {
45717 * Navigate in a given direction.
45719 * @description This method has to be called through EdgeDirection enumeration as in the example.
45721 * @param {EdgeDirection} dir - Direction in which which to move.
45722 * @returns {Promise<Node>} Promise to the node that was navigated to.
45723 * @throws {Error} If the current node does not have the edge direction
45724 * or the edges has not yet been cached.
45725 * @throws {Error} Propagates any IO errors to the caller.
45726 * @throws {Error} When viewer is not navigable.
45730 * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
45731 * (n) => { console.log(n); },
45732 * (e) => { console.error(e); });
45735 Viewer.prototype.moveDir = function (dir) {
45736 var moveDir$ = this.isNavigable ?
45737 this._navigator.moveDir$(dir) :
45738 Observable_1.Observable.throw(new Error("Calling moveDir is not supported when viewer is not navigable."));
45739 return when.promise(function (resolve, reject) {
45740 moveDir$.subscribe(function (node) {
45742 }, function (error) {
45748 * Navigate to a given image key.
45750 * @param {string} key - A valid Mapillary image key.
45751 * @returns {Promise<Node>} Promise to the node that was navigated to.
45752 * @throws {Error} Propagates any IO errors to the caller.
45753 * @throws {Error} When viewer is not navigable.
45757 * viewer.moveToKey("<my key>").then(
45758 * (n) => { console.log(n); },
45759 * (e) => { console.error(e); });
45762 Viewer.prototype.moveToKey = function (key) {
45763 var moveToKey$ = this.isNavigable ?
45764 this._navigator.moveToKey$(key) :
45765 Observable_1.Observable.throw(new Error("Calling moveToKey is not supported when viewer is not navigable."));
45766 return when.promise(function (resolve, reject) {
45767 moveToKey$.subscribe(function (node) {
45769 }, function (error) {
45775 * Project basic image coordinates for the current node to canvas pixel
45778 * @description The basic image coordinates may not always correspond to a
45779 * pixel point that lies in the visible area of the viewer container.
45781 * @param {Array<number>} basicPoint - Basic images coordinates to project.
45782 * @returns {Promise<ILatLon>} Promise to the pixel coordinates corresponding
45783 * to the basic image point.
45787 * viewer.projectFromBasic([0.3, 0.7])
45788 * .then((pixelPoint) => { console.log(pixelPoint); });
45791 Viewer.prototype.projectFromBasic = function (basicPoint) {
45793 return when.promise(function (resolve, reject) {
45794 _this._observer.projectBasic$(basicPoint)
45795 .subscribe(function (pixelPoint) {
45796 resolve(pixelPoint);
45797 }, function (error) {
45803 * Detect the viewer's new width and height and resize it.
45805 * @description The components will also detect the viewer's
45806 * new size and resize their rendered elements if needed.
45813 Viewer.prototype.resize = function () {
45814 this._container.renderService.resize$.next(null);
45815 this._componentController.resize();
45818 * Set a bearer token for authenticated API requests of
45819 * protected resources.
45821 * @description When the supplied token is null or undefined,
45822 * any previously set bearer token will be cleared and the
45823 * viewer will make unauthenticated requests.
45825 * Calling setAuthToken aborts all outstanding move requests.
45826 * The promises of those move requests will be rejected and
45827 * the rejections need to be caught.
45829 * Calling setAuthToken also resets the complete viewer cache
45830 * so it should not be called repeatedly.
45832 * @param {string} [token] token - Bearer token.
45833 * @returns {Promise<void>} Promise that resolves after token
45836 * @throws {Error} When viewer is not navigable.
45840 * viewer.setAuthToken("<my token>")
45841 * .then(() => { console.log("token set"); });
45844 Viewer.prototype.setAuthToken = function (token) {
45845 var setToken$ = this.isNavigable ?
45846 this._navigator.setToken$(token) :
45847 Observable_1.Observable.throw(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
45848 return when.promise(function (resolve, reject) {
45850 .subscribe(function () {
45851 resolve(undefined);
45852 }, function (error) {
45858 * Set the basic coordinates of the current image to be in the
45859 * center of the viewport.
45861 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
45862 * and has the origin point, (0, 0), at the top left corner and the
45863 * maximum value, (1, 1), at the bottom right corner of the original
45866 * @param {number[]} The basic coordinates of the current
45867 * image to be at the center for the viewport.
45871 * viewer.setCenter([0.5, 0.5]);
45874 Viewer.prototype.setCenter = function (center) {
45875 this._navigator.stateService.setCenter(center);
45878 * Set the filter selecting nodes to use when calculating
45879 * the spatial edges.
45881 * @description The following filter types are supported:
45885 * `["==", key, value]` equality: `node[key] = value`
45887 * `["!=", key, value]` inequality: `node[key] ≠ value`
45889 * `["<", key, value]` less than: `node[key] < value`
45891 * `["<=", key, value]` less than or equal: `node[key] ≤ value`
45893 * `[">", key, value]` greater than: `node[key] > value`
45895 * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
45899 * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
45901 * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
45905 * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
45907 * A key must be a string that identifies a node property name. A value must be
45908 * a string, number, or boolean. Strictly-typed comparisons are used. The values
45909 * `f0, ..., fn` of the combining filter must be filter expressions.
45911 * Clear the filter by setting it to null or empty array.
45913 * @param {FilterExpression} filter - The filter expression.
45914 * @returns {Promise<void>} Promise that resolves after filter is applied.
45918 * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
45921 Viewer.prototype.setFilter = function (filter) {
45923 return when.promise(function (resolve, reject) {
45924 _this._navigator.setFilter$(filter)
45925 .subscribe(function () {
45926 resolve(undefined);
45927 }, function (error) {
45933 * Set the viewer's render mode.
45935 * @param {RenderMode} renderMode - Render mode.
45939 * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
45942 Viewer.prototype.setRenderMode = function (renderMode) {
45943 this._container.renderService.renderMode$.next(renderMode);
45946 * Set the image's current zoom level.
45948 * @description Possible zoom level values are on the [0, 3] interval.
45949 * Zero means zooming out to fit the image to the view whereas three
45950 * shows the highest level of detail.
45952 * @param {number} The image's current zoom level.
45956 * viewer.setZoom(2);
45959 Viewer.prototype.setZoom = function (zoom) {
45960 this._navigator.stateService.setZoom(zoom);
45963 * Unproject canvas pixel coordinates to an ILatLon representing geographical
45966 * @description The pixel point may not always correspond to geographical
45967 * coordinates. In the case of no correspondence the returned value will
45970 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
45971 * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
45975 * viewer.unproject([100, 100])
45976 * .then((latLon) => { console.log(latLon); });
45979 Viewer.prototype.unproject = function (pixelPoint) {
45981 return when.promise(function (resolve, reject) {
45982 _this._observer.unproject$(pixelPoint)
45983 .subscribe(function (latLon) {
45985 }, function (error) {
45991 * Unproject canvas pixel coordinates to basic image coordinates for the
45994 * @description The pixel point may not always correspond to basic image
45995 * coordinates. In the case of no correspondence the returned value will
45998 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
45999 * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
46000 * to the pixel point.
46004 * viewer.unprojectToBasic([100, 100])
46005 * .then((basicPoint) => { console.log(basicPoint); });
46008 Viewer.prototype.unprojectToBasic = function (pixelPoint) {
46010 return when.promise(function (resolve, reject) {
46011 _this._observer.unprojectBasic$(pixelPoint)
46012 .subscribe(function (basicPoint) {
46013 resolve(basicPoint);
46014 }, function (error) {
46020 * Fired when the viewing direction of the camera changes.
46022 * @type {number} bearing - Value indicating the current bearing
46023 * measured in degrees clockwise with respect to north.
46025 Viewer.bearingchanged = "bearingchanged";
46027 * Fired when a pointing device (usually a mouse) is pressed and released at
46028 * the same point in the viewer.
46030 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46032 Viewer.click = "click";
46034 * Fired when the right button of the mouse is clicked within the viewer.
46036 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46038 Viewer.contextmenu = "contextmenu";
46040 * Fired when a pointing device (usually a mouse) is clicked twice at
46041 * the same point in the viewer.
46043 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46045 Viewer.dblclick = "dblclick";
46047 * Fired when the viewer is loading more data.
46049 * @type {boolean} loading - Boolean indicating whether the viewer is loading.
46051 Viewer.loadingchanged = "loadingchanged";
46053 * Fired when a pointing device (usually a mouse) is pressed within the viewer.
46055 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46057 Viewer.mousedown = "mousedown";
46059 * Fired when a pointing device (usually a mouse) is moved within the viewer.
46060 * @description Will not fire when the mouse is actively used, e.g. for drag pan.
46062 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46064 Viewer.mousemove = "mousemove";
46066 * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
46068 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46070 Viewer.mouseout = "mouseout";
46072 * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
46074 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46076 Viewer.mouseover = "mouseover";
46078 * Fired when a pointing device (usually a mouse) is released within the viewer.
46080 * @type {IViewerMouseEvent} event - Viewer mouse event data.
46082 Viewer.mouseup = "mouseup";
46084 * Fired when the viewer motion stops and it is in a fixed
46085 * position with a fixed point of view.
46088 Viewer.moveend = "moveend";
46090 * Fired when the motion from one view to another start,
46091 * either by changing the position (e.g. when changing node) or
46092 * when changing point of view (e.g. by interaction such as pan and zoom).
46095 Viewer.movestart = "movestart";
46097 * Fired when the navigable state of the viewer changes.
46099 * @description The navigable state indicates if the viewer supports
46100 * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
46101 * methods. The viewer will not be in a navigable state if the cover
46102 * is activated and the viewer has been supplied a key. When the cover
46103 * is deactivated or activated without being supplied a key it will
46107 * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
46109 Viewer.navigablechanged = "navigablechanged";
46111 * Fired every time the viewer navigates to a new node.
46113 * @type {Node} node - Current node.
46115 Viewer.nodechanged = "nodechanged";
46117 * Fired every time the sequence edges of the current node changes.
46119 * @type {IEdgeStatus} status - The edge status object.
46121 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
46123 * Fired every time the spatial edges of the current node changes.
46125 * @type {IEdgeStatus} status - The edge status object.
46127 Viewer.spatialedgeschanged = "spatialedgeschanged";
46129 }(Utils_1.EventEmitter));
46130 exports.Viewer = Viewer;
46132 },{"../Utils":291,"../Viewer":292,"rxjs/Observable":29,"when":278}]},{},[286])(286)
46134 //# sourceMappingURL=mapillary.js.map